Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 3 Sep 2000 19:49:42 +0100
From:      Ben Smithurst <ben@FreeBSD.org>
To:        Mark Ovens <marko@freebsd.org>
Cc:        questions@freebsd.org
Subject:   Re: perl(1) question
Message-ID:  <20000903194942.V72445@strontium.scientia.demon.co.uk>
In-Reply-To: <20000903190409.B255@parish>
References:  <20000903190409.B255@parish>

next in thread | previous in thread | raw e-mail | index | archive | help
Mark Ovens wrote:

> open 'CONTENTS',"/usr/mark/scrap" or die "cannot open /usr/mark/scrap";

Quotes around a filehandle name?  Looks odd to me, though I guess it
must be legal.

> until (eof 'CONTENTS') {

Loops based on an explicit EOF test like that always seem wrong to me,
and often are in C.  Looking at the manpage it seems this is correct in
Perl at least, but it still looks funny.  Why not use the usual Perl
idiom instead,

while (<CONTENTS>) {
	chomp;

and work with "$_" (which is the default for many things) instead of
"$line".

>     $i = index($line, /FOO/i); 

Dodgy. perlfunc says the second argument is a string, not a regex, but
I'm not that familiar with it.  If so, index will end up searching for
the result of matching /FOO/i against "$_" which isn't defined, so it
will search for undef, which will be converted to the empty string,
which it will always find at offset zero.

I'm not really a Perl guru, but this makes sense to me at least.

> Also, what causes the "Use of uninitialized value...." warning?

See above. :-)

Try something like this:

ben@magnesium:~/tmp$ cat t.pl     
#!/usr/bin/perl -w

while (<STDIN>) {
        if (/FOO/i) {
                printf "match at offset %d\n", length($`);
        } else {
                print "No match\n";
        }
};
ben@magnesium:~/tmp$ cat testdata
foo bar
hello
              foo bar
 foo foo foo
ben@magnesium:~/tmp$ perl -w t.pl < testdata
match at offset 0
No match
match at offset 14
match at offset 1

This assumes I'm understanding your problem correctly.  There may be a
more efficient way to do this, I think using $` and friends is supposed
to be inefficient.

Obviously you'll have to open your file as you did before and use
CONTENTS in place of STDIN, etc, etc...

-- 
Ben Smithurst / ben@FreeBSD.org / PGP: 0x99392F7D


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20000903194942.V72445>