Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

ls piped tpo perl -pe runs indefintely

by ISAI student (Scribe)
on May 01, 2012 at 13:12 UTC ( #968240=perlquestion: print w/replies, xml ) Need Help??
ISAI student has asked for the wisdom of the Perl Monks concerning the following question:

Hello all. I have tried to do something simple. Do ls, pipe it to perl -ne (using xargs) and print. And it runs indefintely. I have tried something simple, like printing out only the directories. See code below

  ls | xargs perl -ne ' map { print $_ , "\n" if ( -d $_ )  ; } @ARGV  '

This runs almost indefintely. However this gets me what I need:

  ls | xargs perl -ne ' $a = shift ; print $a  "\n" if (-d $a) ;  '


Replies are listed 'Best First'.
Re: ls piped tpo perl -pe runs indefintely
by zwon (Abbot) on May 01, 2012 at 13:47 UTC
    You don't need xargs:
    ls | perl -nE'chomp; say $_ if -d $_'
    neither you need ls:
    perl -E'for (<*>) {say $_ if -d $_}'
      Many thanks. It works, and has taught me a lot.

      Maybe a bit more clear:

      perl -E'for (@ARGV) { say $_ if -d $_}' *
Re: ls piped tpo perl -pe runs indefintely
by JavaFan (Canon) on May 01, 2012 at 13:45 UTC
    The second one modifies @ARGV, the first one doesn't. Due to you use of -n (why?), the first one executes the body for every line of the files listed by ls. It should actually terminate, but if you have a lot of large files, this my take a while.

    The second one intends to do the same, that is, execute the body for each of the lines of the files listed by ls, but here you are actually modifying @ARGV, which causes the implicit <ARGV> to terminate after the first iteration.

    My guess is that if you remove the -n, both will do what you want them to do.

Re: ls piped tpo perl -pe runs indefintely
by Anonymous Monk on May 01, 2012 at 13:46 UTC

    shift keeps on reducing the number of elements in @ARGV in the second instance. Thus the while loop (via -n option) ends eventually. See perldoc perlrun, and Deparse ...

    perl -MO=Deparse -ne ' map { print $_ , "\n" if ( -d $_ ) ; } @ARGV +' LINE: while (defined($_ = <ARGV>)) { map {print $_, "\n" if -d $_;} @ARGV; } -e syntax OK

      With respect to the first code instance, if I have (2 directories, 3 files) ...

      ../ ./ p/ q/ r s t

      ... then *nothing* is printed (perl 5.8.8, CentOS 6, zsh 4). If I remove the while loop (-n option), expected output is printed.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://968240]
Front-paged by Corion
and God said, "Let Newton be!"...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2018-03-24 07:04 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (297 votes). Check out past polls.