7

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.