how to access piped-to-perl data?

how to access piped-to-perl data?

am 03.12.2005 15:36:03 von schleifer

Hi *,
I'm trying to process the output of a system command (let that be 'ls' or
'dir' for instance) in perl by piping it to the perl interpreter while
passing the perl program as such in the same command.

Lets say I just want to pipe the directory listing to perl and then outputt
from perl.
I try
--
ls | perl -e " print $_; "
--
but it outputs nothing. I want perl to output the directory listing whichwas
just piped to it.
I'm pretty sure the pipe operator works as it should, so my problem boils
down to how to access the piped input from wthin perl.

any help would be greatly appreciated.
Thanks in advance...

Re: how to access piped-to-perl data?

am 03.12.2005 16:37:53 von Matt Garrish

"A. Schleifer" wrote in message
news:4391ad9b$1_1@news.isis.de...
> Hi *,
> I'm trying to process the output of a system command (let that be 'ls' or
> 'dir' for instance) in perl by piping it to the perl interpreter while
> passing the perl program as such in the same command.
>
> Lets say I just want to pipe the directory listing to perl and then
> outputt from perl.
> I try
> --
> ls | perl -e " print $_; "
> --
> but it outputs nothing. I want perl to output the directory listing
> whichwas just piped to it.

If you don't read stdin, you don't get the input...

ls | perl -e "while () { print \"File: $_\"; }"

> I'm pretty sure the pipe operator works as it should, so my problem boils
> down to how to access the piped input from wthin perl.
>

Although the above works, if you plan to do anything complex with the data
you might want to consider perl's built-in functions (opendir, readdir,
stat, the file test operators, etc). Or, if you absolutely want the shell
command, you can also use open from within your script:

open(my $ls, '-|', 'ls') or die $!;
while (<$ls>) {
print "File: $_";
}
close($ls);

Matt

Re: how to access piped-to-perl data?

am 04.12.2005 10:03:59 von Joe Smith

A. Schleifer wrote:

> I try
> --
> ls | perl -e " print $_; "
> --
> but it outputs nothing.

That's because you neglected to use either the -n or -p switch.

ls | perl -ne 'print "$. $_"'

Or use the 'for' statement modifier.

perl -e 'print ++$n ." $_" for `ls`'

-Joe