You can use the special variable $& to get the whole string that matched. Like this:
if (/^\S+/) { print "$&\n"; }
Or you can put parenthesis around the part that you want to extract, and reference them by $1, $2, etc. Like this:
if (/^(\S+)\s+/) { print "$1\n"; }
Both of the cases above extract any non-whitespace characters at the beginning of the line. Although if that's all you want to do, you are probably better off using split as suggested by others in this thread. It's simpler and probably more efficient. Use regular expressions if you only want to match certain lines that satisfy certain conditions.

So to strictly emulate the shell/awk command line you gave, you can use this:

xcommand | perl -nae 'print $F[0],"\n"'
The -a flag causes it to automatically split each line into whitespace-separated fields, leaving the result in the @F array. The -n option puts a while(<>) { ... } loop around the code. The code itself is specified by the -e option.

From you question, it seems as if you want to provide the command to execute as input to the program. In that case you could do something like this:

my $command="xcommand"; open(CMD, "$command |") or die "Error: $!\n"; while(<CMD>) { print (split(" "))[0]."\n"; # or whatever else } close(CMD);

--ZZamboni


In reply to RE: RE: Re: Help for awk/regex/newbie by ZZamboni
in thread Help for awk/regex/newbie by cmenser

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.