Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: One Liner, print multiple regex matches

by kennethk (Abbot)
on Nov 16, 2012 at 21:43 UTC ( #1004248=note: print w/ replies, xml ) Need Help??


in reply to One Liner, print multiple regex matches

In both those cases, you've got syntax errors. You could modify the second one to use two look-aheads (see Looking ahead and looking behind in perlretut) to grab the fields:

perl -nle ' print "$1$2" if /(?=name=(\w+))(?=age=(\d+))/' filename

Note how your omission of quotes or a comma from your second case means that $1 is being treated at a filehandle.

Your third version fails because you are only allowed one if per statement (see Compound Statements). You could make this work using && and || like:

perl -nle ' /name=(\w+)/ && print($1) || /age=(\d+)/ && print($1) ' filename

or, use two different statements to make it even easier:

perl -nle 'print $1 if /name=(\w+)/; print $1 if /age=(\d+)/' filename

Note that you are using two different regular expressions, so each one would set the $1 buffer if it matches.

As a last comment, assuming you are running a reasonably recent version of perl, your output might be easier to deal with if you use -E in place of -e and swap your prints to says (see perlrun).

Oh, and please wrap input data in <code> tags, as white space is mangled on display if you don't.


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: One Liner, print multiple regex matches
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1004248]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2015-07-03 22:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (57 votes), past polls