Home: Perl Programming Help: Beginner:
Match Doesn't???



airman
Deleted

Mar 14, 2001, 9:33 AM


Views: 1266
Match Doesn't???

Can't seem to figure out why the following doesn't work. I would greatly appreciate any help. I have opened and read the file into @lines at this point.

for ($i = 1; $i < @lines; $i++){
if ($lines =~ m/message/){
print "$lines[$i]";
}
}

Doesn't seem to match and print the following line or lines like it. I know the lines are there as I comment out the IF statement and everything prints fine.

<font SIZE=2>Why won't it work?</font>










izzy
stranger

Mar 14, 2001, 11:54 AM


Views: 1264
Re: Match Doesn't???

It should be like this. you are missing [$i] in the match
for ($i = 1; $i < @lines; $i++){
if ($lines[$i] =~ m/message/){
print "$lines[$i]";
}
}




japhy
Enthusiast

Mar 14, 2001, 5:13 PM


Views: 1258
Re: Match Doesn't???

What in the world do you expect $lines =~ m/message/ to do? You should be checking $lines[$i], not $lines.

And you're skipping the first element. Arrays start 0, not 1.

And you're coding Perl as if it were C. Please don't do that.


Code
for (@lines) { 
if (/message/) {
print;
}
}

# or

for (@lines) {
print if /message/;
}

# or

print grep /message/, @lines;

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author