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.


In reply to Re: One Liner, print multiple regex matches by kennethk
in thread One Liner, print multiple regex matches by cipher

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.