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
|