http://qs1969.pair.com?node_id=85907


in reply to How do I store all matches from a single line?

I'd try something like: @array = /<(\w+\@\w+\.\w+)>/g;

Replies are listed 'Best First'.
Re: Re: pattern matching on a single line
by merlyn (Sage) on Jun 05, 2001 at 22:38 UTC
    That's incorrect for actual email addresses. If you just want all the angled parts of all the lines, it's something as simple as:
    @result = map /<.*?>/g, @lines;

    -- Randal L. Schwartz, Perl hacker

      I thought @second = map EXPR, @first; applied EXPR to each element of @first and placed the results in @second. And since m// doesn't change anything, then @second would equal @first.

      So something like:

      for (@lines) { @result = /<(.*?)>/g; }


      Would be more appropriate.

      However, I'm willing to bet heavily that your Perl knowledge far exceeds mine, so I'm wondering: do I misunderstand map or m// (or both)?



      FouRPlaY
      Learning Perl or Going To die() Trying

        The return value of m/()/g in array context (which map evaluates EXPR in) is the array containing all the matches inside the parentheses, just like in your first reply. The only difference that the map makes is that merlyn is evaluating the m/()/g for every line, while yours only did one line.

        HTH.

        bbfu
        Seasons don't fear The Reaper.
        Nor do the wind, the sun, and the rain.
        We can be like they are.

        map actually returns the result of EXPR in LIST context. That means each evaluation of

        /<(.*?)>/g

        returns the list of captured items. So in effect we get

        @result = ( ( result of evaluating first element ), ( result of evaluating second element ), ....);

        So the resulting array is one big array with all of the matches that EXPR produced

        He's using map to collect the results into one list. Like foreach, it will iterate over the list specified at the right. But it will also collect together the results into one list. The regex content will return a list of all matches made (thanks to /g), and map will nicely concatenate all those together into one big list.

        Sadly your example fails to produce the desired result :-( Here are a few different ways to write it, all do the same as Randal's example, which we start with.

        tachyon

        @lines = <DATA>; @result = map /<.*?>/g, @lines; result(1); for (@lines) { @result = /<(.*?)>/g; } result(2); for (@lines){ @match = /<(.*?)>/g; push @result, @match; } result(3); for (@lines){ push @result,$1 while /<(.*?)>/g; } result(4); @result = map{/<.*?>/g}@lines; result(5); sub result { print"\nResults",pop,"\n"; print "$_\n" for @result; @result = (); } __DATA__ aa<aa@aa.com>bb<bb@bb.com>cc<cc@cc.com> dd<dd@dd.dd>ee<ee@ee.com>ff<ff@ff.com>