Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All

If i issue the command ls /home/virtual/test.com/home/ | wc -l | awk '{print $1}' at the command line, it returns 91, but if i want to put that into a perl script as a variable like this $users  = `ls /home/virtual/xms.ms/home/ | wc -l | awk '{print $1}'` it returns ____91 (_ = space). Any ideas why it is putting those spaces in front of the output? it looks like it is ingnoring the | awk '{print $1}' part of the line!

Help!

Replies are listed 'Best First'.
Re: Runing Command
by BrowserUk (Patriarch) on Dec 20, 2002 at 14:59 UTC

    I can't answer why, but if you are counting users by the number of directories off the path supplied, the there is no need to go to all that trouble.

    $users = grep{ -d $_ } glob('/home/virtual/xms.ms/home/*');

    Would probably be heaps quicker.


    Examine what is said, not who speaks.

Re: Runing Command
by hardburn (Abbot) on Dec 20, 2002 at 14:59 UTC

    The `` quotes interpoloates variables. Specificly, the "$1" bit in the awk part of your pipeline is probably being interpreted as an empty string (unless you've done some capturing matches in the Perl code, which I'm guessing you haven't). You'll need to escape that part ("\$1").

Re: Runing Command
by derby (Abbot) on Dec 20, 2002 at 15:11 UTC
    TMTOWTDI:

    #!/usr/bin/perl -w opendir( DIR, $ARGV[0] ) || die "canot open $ARGV[0] ($!)\n"; map { $cnt++ unless /^\./ } readdir( DIR ); closedir( DIR ); print $cnt, "\n";

    -derby

      Yuck, map in void context. :) !/^\./ and $cnt++ for readdir( DIR ); And actually, I'd rather use a grep in scalar context: $cnt = grep !/^\./, readdir DIR;

      Makeshifts last the longest.