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.
The Perl grep() function is a filter that runs a regular expression on each element of an array and returns only the elements that evaluate as true. Using regular expressions can be extremely powerful and complex. The grep() functions uses the syntax @List = grep(Expression, @array).
The grep equivalent would be $idx = grep { $array[$_] eq 'whatever' and last } 0 ..
shift. Shifts all the values of an array on its left. unshift. Adds the list element to the front of an array.
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.
It is the global /g
modifier that is at work. It remembers the position of the last pattern match. When it reaches the end of the string, it starts over.
Remove the /g
modifier, and it will act as you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With