For Programmers: Free Programming Magazines  


Home > Archive > PERL Programming > December 2005 > how to access piped-to-perl data?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author how to access piped-to-perl data?
A. Schleifer

2005-12-03, 6:56 pm

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...


Matt Garrish

2005-12-03, 6:56 pm


"A. Schleifer" <schleifer@mailinator.com> 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 (<STDIN> ) { 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


Joe Smith

2005-12-04, 3:56 am

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
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com