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

I have the following code, I am trying to get the number of jobs returned to me in $server_num_jobs. But $server_num_jobs keeps returning 1. I have tried several variations on the code such as $server_num_jobs=`/usr/bin/lpstat -h $server -W not-completed |wc -l`; amongst others.
#!/usr/bin/perl -w use strict; use diagnostics; use Data::Dumper;
snip ...
my @cups_num_jobs_cmd=("/usr/bin/lpstat ", "-h", $server, "-W not-comp +leted"); print Dumper "cmd = @cups_num_jobs_cmd"; my @cups_num_jobs=system(@cups_num_jobs_cmd); print Dumper "cups_jobs = @cups_num_jobs"; $server_num_jobs=scalar(@cups_num_jobs); print Dumper "server_num = $server_num_jobs";
$server is the name of a cups server
I don't get any errors from the code, but what I am trying to do is to get the number of jobs back ie 3. If I run the command from the command line I get back three jobs as in the following:
R_NETADMIN_NB-46 root 15360 Wed 16 Mar 2005 01:05 +:25 PM EST RSPARE_NB-47 root 15360 Wed 16 Mar 2005 01:05 +:33 PM EST RSPARE_NB-48 root 15360 Wed 16 Mar 2005 01:05 +:38 PM EST

Replies are listed 'Best First'.
Re: Number of lines from a system call
by RazorbladeBidet (Friar) on Mar 16, 2005 at 19:01 UTC
    system returns the return code from the call.

    you probably want backticks (qx//)

    See system and qx//
    --------------
    It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
      Ive tried using backticks I think its not interpreting the $server variable. in this test script its fine
      #!/usr/bin/perl -w use strict; use diagnostics; use Data::Dumper; my $server="rprint1"; my $num = qx{/usr/bin/lpstat -h $server -W not-completed|wc -l}; print Dumper "$num"; my $server1='rlinux1'; my $num2 = qx{/usr/bin/lpstat -h $server1 -W not-completed|wc -l}; print Dumper "$num2";
      produces
      $VAR1 = 'rprint1'; $VAR1 = '2 '; $VAR1 = 'rlinux1'; $VAR1 = '3 ';
      but from the original script
      print Dumper "$server"; my $server_num_jobs = qx{/usr/bin/lpstat -h $server -W not-compl +eted|wc -l}; print Dumper "$server_num_jobs";
      produces
      $VAR1 = 'rprint1'; $VAR1 = '0 '; $VAR1 = 'rlinux1'; $VAR1 = '0 ';
        If you use backticks in scalar context, like you do, you'll get the whole output in one string. If you use them in list context, you'll get the lines of output as a list.
        So what you need is:
        my $num = () = qx{/usr/bin/lpstat -h $server -W not-completed};
        which puts the number of lines output by the command into $num.
        This syntax puts qx{...} into list context and returns the number of elements in the list rather than the list itself.

        Besides, why are you using Data::Dumper? This is nice for structured variables, but for plain strings it's more straightforward to write:

        print "number is: $num\n";