in reply to Unable to use if condition inside foreach loop using perl?
Hello finddata
I think everyone is trying to explain that the way that you have defined your regular expression will not work. The reason:
foreach my $temp_line(@store_files) { if(my $pattern =~ /^REVISION_LOCATION:/){
Simply you are comparing against an empty string. It is like you are doing if('' =~ /^REVISION_LOCATION:/){, when you should be doing something like: if($temp_line =~ /^REVISION_LOCATION:/){.
If still is not clear enough read the perlrequick it will give a quick understanding about regex.
Sample of replicating your error:
#!/usr/bin/perl use strict; use warnings; my $dir = shift // '.'; opendir my $dh, $dir or die "Could not open '$dir' for reading '$!'\n"; my @things = grep {$_ ne '.' and $_ ne '..'} readdir $dh; foreach my $thing (@things) { if(my $pattern =~ /^test/){ print $thing . "\n"; } } closedir $dh or die "Could not close dir hanlde '$dh': '$!'\n"; __END__ Monks$ perl test.pl Use of uninitialized value $pattern in pattern match (m//) at test.pl +line 11. Use of uninitialized value $pattern in pattern match (m//) at test.pl +line 11.
I would also recommend to refactor a bit your code an use readdir .
Sample from my localhost with no error:
#!/usr/bin/perl use strict; use warnings; my $dir = shift // '.'; opendir my $dh, $dir or die "Could not open '$dir' for reading '$!'\n"; my @things = grep {$_ ne '.' and $_ ne '..'} readdir $dh; foreach my $thing (@things) { if($thing =~ /^test/){ print $thing . "\n"; } } closedir $dh or die "Could not close dir hanlde '$dh': '$!'\n"; __END__ Monks$ perl test.pl test.pl~ test.pl
|
|---|