I have a strange problem when matching a template.
Consider the Perl code below
#!/usr/bin/perl -w use strict; my @Array = ("Hello|World","Good|Day"); function(); function(); function(); sub function { foreach my $pattern (@Array) { $pattern =~ /(\w+)\|(\w+)/g; print $1."\n"; } print "\n"; } __END__
Expected result should be
Hello
Good
Hello
Good
Hello
Good
But I get
Hello
Good
Use of uninitialized value $ 1 in concatenation (.) Or string at D: \ perlfiles \ problem.pl li
ne 28.
Use of uninitialized value $ 1 in concatenation (.) Or string at D: \ perlfiles \ problem.pl li
ne 28.
Hello
Good
What I observed was that the pattern matched the alternative.
Can someone explain to me what the problem is with this code. To fix this, I changed the function subroutine to something like this:
sub function { my $string; foreach my $pattern (@Array) { $string .= $pattern."\n"; } while ($string =~ m/(\w+)\|(\w+)/g) { print $1."\n"; } print "\n"; }
Now I get the output as expected.
vels
source share