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

Hi

Please forgive if this is a stupid question but I'm a bit stuck and wondered if you could help?

I have a perl program that gets information about running processes on a server. I have a command that works on the command line but I can't get it to work in my perl script.

The command that works on the command line is:

ps aux | grep java | perl -e 'while(<STDIN>){if (/-Xmx((\d+)[gG])/) { +$mem += $2 } } print "total memory reserved by Java processes: ${mem} +G\n"'

Which gives me: total memory reserved by Java processes: 58G

If I post this into my perl script no matter how I tweak it I can't get it to work.

Can you please help?

Replies are listed 'Best First'.
Re: Running a command in Perl
by davido (Cardinal) on Jan 28, 2014 at 16:52 UTC

    You didn't mention specifically what you tried, and in what way it fails, so it's hard to diagnose what you're doing wrong. Does this work for you?

    foreach(`ps aux | grep java`){ if (/-Xmx((\d+)[gG])/) { $mem += $2 } } print "total memory reserved by Java processes: ${mem}G\n"

    Dave

Re: Running a command in Perl
by Tux (Canon) on Jan 28, 2014 at 17:37 UTC

    Why not use Proc::ProcessTable:

    $ cat mem.pl use 5.12.1; use warnings; use Data::Peek; use Proc::ProcessTable; my $s; $s += $_->{size} for grep { $_->cmndline =~ /java/ } @{Proc::ProcessTa +ble->new->table}; say $s; $ perl mem.pl 27656867840

    Enjoy, Have FUN! H.Merijn
Re: Running a command in Perl
by Laurent_R (Canon) on Jan 28, 2014 at 19:45 UTC
    Launching a Perl one-liner within a shell system command launched itself by another Perl program seems to be poor design. If you really want to call a system command from your Perl script just issue this system command:
    ps aux | grep java
    and process the output within your other Perl script with the commands you have in your one-liner. Although the filtering made by the grep shall command could itself be done within the Perl script. And then, of course, there are also some pure Perl solutions using modules.