http://www.perlmonks.org?node_id=1016713


in reply to How to store matched $1 values one by one to array?

Note that another, perhaps safer, way of capturing everything after "agent_id=>" up to but not including a comma is to use use a negated character class ([^,]+) meaning one or more of anything that isn't a comma rather than a non-greedy match of anything (.+?). You can also populate your array, let's call it @agents, in one fell swoop by using a global match (g flag) and a map within which we substitute away the double-quotes.

$ perl -Mstrict -Mwarnings -MData::Dumper -e ' > my $line = > q{xxx:agent_id=>foo,yyy:agent_id=>b"a"r,zzz:agent_id=>"baz",qqq}; > > my @agents = > map { s{"}{}g; $_ } > $line =~ m{ :agent_id=> ( [^,]+ ) }xg; > > print Data::Dumper->Dumpxs( [ \ @agents ], [ qw{ *agents } ] );' @agents = ( 'foo', 'bar', 'baz' ); $

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: How to store matched $1 values one by one to array?
by AnomalousMonk (Archbishop) on Feb 02, 2013 at 14:01 UTC

    A minor variation using the  \K (5.10+) and  s///r (5.14+) regex operators, and no capture groups. (Note: I use  \x22 instead of  " (double-quote) in the  s///r substitution because the Windoze CLI gets a little freaky over unpaired double-quotes.)

    >perl -wMstrict -MData::Dump -le "my $line = q{xxx:agent_id=>foo,yyy:agent_id=>b\"a\"r,zzz:agent_id=>\"baz\",qqq +}; ;; my @agents = map s{\x22}{}xmsgr, $line =~ m{ :agent_id=> \K [^,]+ }xmsg; ;; dd \@agents; " ["foo", "bar", "baz"]