RE: beginners-help@perl.org



On Thu, 27 Dec 2007 10:46:42 -0500, Clifton Lee wrote:
The output from the system command may be better stored in a scalar and then
split into an array (separated by return line characters). Then you can use
the 'foreach' operator for each element in your array.

That makes no sense. Perl will supply a list of lines when you call the
backticks operator (not system command) in list context; why add the
unnecessary step?

@arr1 = qw/java oracle/;
$scalar = `ps -eo pid,user,pcpu,pmem,args | grep -v grep | grep $arr1[1]`;
@arr2 = split(/\n/,$scalar);
$length = $#arr2;

$length is not used.

foreach my $val (@arr2)
{
# get rid of the leading space for each line if one exists

split can do that for you.

$val =~ s/^\s//;

@arr = split(/\s+/,$val);
print $arr[1]."\n";
}

my @arr1 = qw/java oracle/;
for (`ps -eo pid,user,pcpu,pmem,args | grep -v grep | grep $arr1[1]`)
{
my @arr = split;
print "$arr[1]\n";
}

That strictly matches the original code, but John's embellishments of
limiting the split fields and searching only the user field make it
better. One could also use Proc::ProcessTable from CPAN to remove the
dependency on the ps program (questionable benefit).

--
Peter Scott
http://www.perlmedic.com/
http://www.perldebugged.com/

.



Relevant Pages

  • Re: help with array within another array
    ... here you're pushing to an array that perl has never heard of, @SESSION, ... so perl goes ahead and makes an empty one for you before it pushes your ... (A hash in list context is just a list.) ...
    (perl.beginners)
  • Re: Learning Perl
    ... it should be an array, ... Then they'd be completely inaccessible to beginners. ... that should be my $var. ... so why is it redundant to point out that Perl is different from C here? ...
    (comp.lang.perl.misc)
  • Re: Which is faster - hash or array lookup
    ... I am suite sure that perl is not The Right Tool ... Each player has 5 pieces, and additionally there is a common ... whereas traversing an array looking for $n is slow). ...
    (comp.lang.perl.misc)
  • Re: perl vs Unix grep
    ... variable indexCount on array and reintialized evry time. ... Perl is langauge to make things work at any cost. ... > grep but the shell scripts that use ... As far as I can tell from reading and research ...
    (comp.lang.perl)
  • FAQ 4.42 How can I tell whether a certain element is contained in a list or array?
    ... comes with the standard Perl distribution. ... How can I tell whether a certain element is contained in a list or array? ... used a hash, not a list or array, to store your data. ... The perlfaq-workers, a group of volunteers, maintain the perlfaq. ...
    (comp.lang.perl.misc)