Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i hav a tcl file

now , i haw certain commands in an array!, i want to extract the line number fron file where there commands are... so i m comparing it but its not working....so far i m doing this:

<while(<FILE>){ $var1=$_; foreach my $var2 (@array){ if($var1 eq $var2){ print "line is $.\n"; } } }>
it doesen't returm me any match....... i even tried with grep but it is also not working.......

can anyone help me with this!!!!!!!!

Nidhi.

Replies are listed 'Best First'.
Re: comparing array vs file
by wfsp (Abbot) on Aug 05, 2008 at 06:56 UTC
    This may be caused by not taking account of newlines on the lines read from the file. Include a chomp and see if that helps.
    #!/usr/local/bin/perl use strict; use warnings; my @array = qw{one three}; while(<DATA>){ my $var1=$_; chomp $var1; foreach my $var2 (@array){ if($var1 eq $var2){ print "line is $.\n"; } } } __DATA__ one two three four
Re: comparing array vs file
by cdarke (Prior) on Aug 05, 2008 at 07:08 UTC
    To add to wsfp's excellent answer, this is an almost classic case where a hash will make the code simpler and (probably) quicker:
    #!/usr/local/bin/perl use strict; use warnings; my %hash; @hash{qw(one three)} = undef; while(my $var1 = <DATA>){ chomp $var1; if (exists $hash{$var1}) { print "line is $.\n"; } } __DATA__ one two three four