On Dec 27, 2007 10:46 AM, Clifton Lee <[EMAIL PROTECTED]> wrote: > Hello, > > 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. > > @arr1 = qw/java oracle/; > $scalar = `ps -eo pid,user,pcpu,pmem,args | grep -v grep | grep $arr1[1]`; > @arr2 = split(/\n/, $scalar); > $length = $#arr2; > > foreach my $val (@arr2) > { > # get rid of the leading space for each line if one exists > $val =~ s/^\s//; > > @arr = split(/\s+/,$val); > print $arr[1]."\n"; > } snip
The solution using the open function that John posted has the benefit that it is using a pipe. This means you will start to receive data as soon as it is written*. If you use the qx// operator (aka backticks or ``) you will have to wait for the subprocess to finish. In some cases this doesn't matter, in others it is vital. Using open also allows you to only store the data you actually want. Lets say you want to run a command that could return four gigs worth of data. If you use the qx// operator, you are in trouble. With the open solution you just read a line** at a time. Also, the qx// operator in list context returns the output as a list of lines, so you can say my @arr2 = `command`; and save yourself the split. Which brings me to my last point. Your example was written as if the strict and warning pragmas were not in effect. This is an extremely bad idea (for one thing, strict would catch that you used @arr in the loop instead of @arr1). * well, as soon as the buffer is full ** well, actually you read in up to (and including) the string*** in $/. *** if $/ holds a reference to a scalar, then that number is used as the maximum number of bytes to read in -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/