[HRPM] Sorting and array of lines returned from 'ps'
chicks at chicks.net
chicks at chicks.net
Tue Nov 21 10:04:52 CST 2000
On Tue, 21 Nov 2000, Scott Cornette wrote:
> Once you have decided on which field you want sorted, you can try
> sorting the array using the perl sort operator with a subroutine
> passed as an argument. This will allow you to do comparisons by
> choosing whether you want a numeric or ASCII sort. For example, to
> sort a numeric field:
>
> sub numerically { $a <=> $b; }
>
> @sorted_array = sort numerically @unsorted_array;
>
> To sort a field of strings (ASCII based):
>
> sub ascii_string { $a cmp $b; }
>
> @sorted_array = sort ascii_string @unsorted_array;
>
> There are plenty of examples in the Camel book and Cookbook.
That's precisely what I was thinking of doing for him. But instead of a
single operation like ascii_string (which is redundant since that's 'cmp'
is what sort uses by default!) ... I was thinking of something like:
sub pid_array {
($x,$x,$x,$pida) = split (/ /,$a);
($x,$x,$x,$pidb) = split (/ /,$b);
$pida <=> $pidb;
}
@sortedprocs = sort pid_array @rawprocs;
Two things are relevant here:
- The value of the last line of a sub is used as the return value if there
is no explicit return value. This is a side effect and isn't as explicit
as I'd like, but it's common practice and it's good to be familiar with
it.
- <=> and cmp are special in that they return -1 for less than, 0 for
equal and 1 for greater than -- which is exactly what sort needs. If your
sub returns those values consisantly, you don't need to use those
operators to generate them.
And as everyone has said the Camel (/Programming Perl/) and the Cookbook
have lot's of useful information. I've got Camel 3E on my night stand
and I'm hoping to dig into in the next few weeks!
--
</chris> (My God, there's HRPM list traffic! Yay.)
"Pinky, you've left the lens cap of your mind on again." - The Brain
More information about the Norfolk-pm
mailing list