Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl pattern matching when using arrays

Tags:

regex

perl

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.

like image 782
vels Avatar asked Mar 13 '12 03:03

vels


People also ask

How do I match an array pattern in Perl?

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).

How do you find the index of an array element in Perl?

The grep equivalent would be $idx = grep { $array[$_] eq 'whatever' and last } 0 ..

What is shift and Unshift in Perl?

shift. Shifts all the values of an array on its left. unshift. Adds the list element to the front of an array.

Does Perl use regex?

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“.


1 Answers

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.

like image 115
TLP Avatar answered Oct 17 '22 03:10

TLP