Awk Anomaly

For discussions about programming and projects not necessarily associated with Porteus.

Awk Anomaly

Postby Bogomips » 25 Jan 2015, 21:38

Don't see how this can be explained as not being a bug :unknown:
Code: Select all
guest@porteus:~$ awk 'BEGIN{print "+"x y"+"; print index(x,y)}'
++
1
guest@porteus:~$ awk 'BEGIN{x="lib";print "+"x y"+"; print index(x,y)}'
+lib+
1
guest@porteus:~$ awk 'BEGIN{x="lib";print "+"x y"+"; print index(x,"l")}'
+lib+
1
Logically the null string should match position zero, giving an index of 0, as one would expect.
Linux porteus 4.4.0-porteus #3 SMP PREEMPT Sat Jan 23 07:01:55 UTC 2016 i686 AMD Sempron(tm) 140 Processor AuthenticAMD GNU/Linux
NVIDIA Corporation C61 [GeForce 6150SE nForce 430] (rev a2) MemTotal: 901760 kB MemFree: 66752 kB
Bogomips
Full of knowledge
Full of knowledge
 
Posts: 2370
Joined: 25 Jun 2014, 16:21
Location: London
Distribution: 3.2.2 Cinnamon & KDE5

Re: Awk Anomaly

Postby port » 22 Feb 2016, 11:25

It's not an anomaly but normal behaviour.

awk string begin in index 1 not 0. Function index returns the position of first character of string to find that is a number >= 1 or number 0 if no occurrence found.

When you look for null string in another string, you always find the null string at first position ;-)

Code: Select all
guest@porteus:~$ awk 'BEGIN{x="a non-empty string"; print index(x,"");}'
1
guest@porteus:~$ awk 'BEGIN{x=""; print index(x,"");}'
1
guest@porteus:~$ awk 'BEGIN{x="hal"; print index(x,"p");}'
0
guest@porteus:~$ awk 'BEGIN{x=""; print index(x,"p");}'
0
port
Black ninja
Black ninja
 
Posts: 99
Joined: 18 Feb 2016, 10:25
Location: Spain
Distribution: Linux porteus 3.2.2 KDE


Return to Programming



Who is online

Users browsing this forum: No registered users and 1 guest