I have a strange problem in matching a pattern.
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__
The output I expect should be
Hello Good Hello Good Hello Good
But what I get is
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 matches alternatively.
Can someone explain me what is the problem regarding 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.