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

Hi guys/girls, I have an issue with the sytem command not returning what I expect. If I run the following code on a command line (unix), all is good:
cat /proc/net/dev|grep eth0|awk '{print $2}'|sed 's/eth0://g'
this produces
1264133390

However, as soon as I wrap it in a system command
system ("`cat /proc/net/dev|grep eth0|awk '{print $2}'|sed 's/eth0://g +'`");
I get:
1186039385 106 2573409268 1264144206 0 0 0 0 0 0 1138115089 911959888 37 0 0 729406590
It seems that the pipes are not being executed, but I can't figure out why. Does anyone have any ideas?

Replies are listed 'Best First'.
Re: system command question
by citromatik (Curate) on Aug 02, 2007 at 08:07 UTC

    It is fairly easy to translate your system call to pure perl:

    use strict; use warnings; open my $dev, "<", "/proc/net/dev" or die $!; my ($eth0) = grep {/eth0/} <$dev>; close $dev; my $k = (split /\s+/,$eth0)[1]; $k =~ s/eth0://g; print "$k\n";

    Outputs:

    190722498
Re: system command question
by salva (Canon) on Aug 02, 2007 at 07:50 UTC
    You probably want to use:
    system q{cat /proc/net/dev|grep eth0|awk '{print $2}'|sed 's/eth0://g' +};
    or
    my $result = `cat /proc/net/dev|grep eth0|awk '{print \$2}'|sed 's/eth +0://g'`;
Re: system command question
by roboticus (Chancellor) on Aug 02, 2007 at 12:07 UTC

    One other item: You don't really need the cat statement, as grep can read from the file just as easily as it can read from the pipe:

    grep eth0 /proc/net/dev | awk '{print $2}' | sed 's/eth0://g'

    then, of course, you really don't need the grep, either, as awk knows how to run a block only when it finds a regular expression:

    awk '/eth0/ {print $2}' /proc/net/dev | sed 's/eth0://g'

    After that, we don't really need the sed statement either, as awk can also do a regular expression substitution:

    awk '/eth0/ {print gensub("eth0","","g",$2); }' /proc/net/dev'
    Of course, since this is a perl site, you might just want to use perl...

    ...roboticus

Re: system command question
by andreas1234567 (Vicar) on Aug 02, 2007 at 08:05 UTC
Re: system command question
by andreas1234567 (Vicar) on Aug 02, 2007 at 12:40 UTC
    ..or use the already available Linux::net::dev:
    $ perl use strict; use warnings; use Linux::net::dev; use Data::Dumper; my $devs = Linux::net::dev::info(); foreach my $key (keys %$devs) { print $key . ": ". Dumper($devs->{$key}) if ($key eq q{eth0}); } __END__ eth0: $VAR1 = { 'rcompressed' => '0', 'tbytes' => '500984059', 'rpackets' => '2007663', 'tfifo' => '0', 'rfifo' => '0', 'terrs' => '0', 'rmulticast' => '0', 'tdrop' => '0', 'tpackets' => '1283040', 'rdrop' => '0', 'rframe' => '0', 'tcolls' => '0', 'tcarrier' => '0', 'tcompressed' => '0', 'rerrs' => '0', 'rbytes' => '1500560631' };
    --
    Andreas