perl(1) question

Paul Richards paul at originative.co.uk
Sun Sep 3 23:22:12 BST 2000


Mark Ovens wrote:
> 
> Does index() ignore leading whitespace? A perl(1) script I have
> appears to be doing just that. Isolating the relevant lines I have:

index() is working fine, the code has a number of flaws.

> #!/usr/bin/perl -w
> 
> open 'CONTENTS',"/usr/mark/scrap" or die "cannot open /usr/mark/scrap";
> 
> until (eof 'CONTENTS') {
>     chomp ($line = <CONTENTS>);
>     $i = index($line, /FOO/i);
>     print "line\=$line\n";
>     print "i \= $i\n";
> };
> 
> close 'CONTENTS';

The two parameters to index are the string to be searched in, and the
string to be searched for. In this case the string to be searched in is
$line and the string to be searched for is the result of the match
expression /FOO/i. Flaw number one is that /FOO/i will try and match
against $_ which is never assigned to in this little script and that is
why you're getting the uninitialised warnings. Flaw number 2 is that
even if $_ was defined, or you matched specifically against some other
variable, the result of the expression is either 1 for a match or "" if
not. Since in the above code is trying to match against $_ which is
undefined the result will always be "" which never matches anything so
index() always returns 0.

Paul.




More information about the Ukfreebsd mailing list