0

My syntax is

my $pstree = `pstree -p $pid|wc`;

but i am getting an error.

sh: -c: line 1: syntax error near unexpected token `|'

any thoughts?

ysth
  • 96,171
  • 6
  • 121
  • 214

3 Answers3

2

Your variable $pid isn't just a number; it probably has a trailing newline character.

See it with:

use Data::Dumper;
print Data::Dumper->new([$pid])->Terse(1)->Useqq(1)->Dump;
ysth
  • 96,171
  • 6
  • 121
  • 214
1

It's valid perl, your shell is what is complaining. Did you put the #!/bin/perl at the top of the script? It's probably being interpreted by bash, not perl.

host:/var/tmp root# ./try.pl
5992  zsched
  6875  /usr/local/sbin/sshd -f /usr/local/etc/sshd_config
    3691  /usr/local/sbin/sshd -f /usr/local/etc/sshd_config -R
      3711  -tcsh
        6084  top 60
===
       5      16     175


host:/var/tmp root# cat try.pl 
#!/bin/perl

my $pstree = `ptree 3691`;
my $wc = `ptree 3691 | wc`;
print STDOUT $pstree;
print STDOUT "===\n";
print STDOUT $wc;
Mark Solaris
  • 123
  • 1
  • 6
1

Instead of using the shell to do your counting, you can use Perl, which saves you a process and some complexity in your shell command:

my $count = () = qx(pstree -p $pid);

qx() does the same thing as backticks. The empty parentheses puts the qx() in list context, which makes it return a list, which then in scalar context is the size. It is a shortcut for:

my @list  = qx(pstree -p $pid);
my $count = @list;
TLP
  • 66,756
  • 10
  • 92
  • 149