Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I would like to match the first lean : sigma and the second lean : sigma from this array using pattern matching. Please help me on this.
@arr = ('lean : sigma', 'none', 'lean : sigma'); Expected Ouput: First match=> learning : enable Second match => learning : enable

Replies are listed 'Best First'.
Re: match array content of first and second match
by sierpinski (Chaplain) on Dec 13, 2010 at 13:29 UTC
    You've posted your array, and your expected output, can you post the code that hasn't produced that expected output? That'll help loads in determining what you may be doing wrong (learning experience) or even if there is a better way of doing it.
Re: match array content of first and second match
by Anonymous Monk on Dec 14, 2010 at 04:54 UTC

    The code which i have tried is, please guide me.

    if (@arr =~ /^learning : enable){ print "First content=> $_"; }

      What I don't understand: The line in @arr has nothing in common with what you are printing. Where do you find the 'enable' string? Your problem description is very inconsistent

      First of all you need a loop, you can't use a regex on an array. This can be done with an implicit loop like this:

      @results= map(/^(lean : sigma)/,@arr); print "First content=> $_\n" for @results;

      or explicit with:

      foreach (@arr) { if (/^(lean : sigma)/) { print "First content=> $1\n"; } }

      The regex will return whatever is inbetween the '()', if this is not a constant expression, substitute it with .* and it will get you anything till the end of line

      Note this will print 'First content' for every match. If you want to have 'first', 'second', 'third'... you need to list those strings to perl since perl doesn't know about natural languages like english. So you would need something like this

      @numberlist=('First','Second','Third','Fourth','Fifth'); #and so on as + high as the maximal number of matches you expect @results= map(/^(lean : sigma)/,@arr); $i=0; foreach (@results) { print $numberlist[$i++]," content=> $_\n"; }