in reply to grep or exists

hi

(untested)

#!/usr/bin/perl use strict; use warnings; use Proc::ProcessTable; my $p=Proc::ProcessTable->new; my $wanted=1234; print "Found\n" if grep(/^$wanted$/,@{$p->table} );

"Keep pouring your ideas"

Replies are listed 'Best First'.
Re^2: grep or exists
by bart (Canon) on May 16, 2006 at 12:44 UTC
    grep(/^$wanted$/,@{$p->table} )
    There is abolutely no need to limit use of grep in Perl to regular expressions. Any kind of boolean expression, or expression used as a boolean, for the filter condition, will do. For example:
    grep($_ == $wanted, @{$p->table} )
    update: Better, as blazar points out, code that actually works for this case:
    grep($_->pid == $wanted, @{$p->table} )
Re^2: grep or exists
by blazar (Canon) on May 16, 2006 at 12:47 UTC

    That way it won't work:

    $ perl -MProc::ProcessTable -le 'print for @{Proc::ProcessTable->new-> +table}' Proc::ProcessTable::Process=HASH(0x814cb3c) Proc::ProcessTable::Process=HASH(0x827d44c) Proc::ProcessTable::Process=HASH(0x8276e84) Proc::ProcessTable::Process=HASH(0x827d590) Proc::ProcessTable::Process=HASH(0x8276f74) Proc::ProcessTable::Process=HASH(0x8277890) Proc::ProcessTable::Process=HASH(0x8277a40) Proc::ProcessTable::Process=HASH(0x8277bf0) ...

    Your match has to become

    $_->pid =~ /^$wanted$/

    But even then it would be an abuse of grep and of a pattern match, IMHO. Both slightly suboptimal, for

    • the implicit grep cycle will continue also after the pid has been matched;
    • the match is either less efficient than a comparison or optimized to a comparison, I can't remember which is which. In any case why not going for an explicit comparison to begin with?
Re^2: grep or exists
by Anonymous Monk on May 16, 2006 at 13:15 UTC
    A question I have about both of these answers is what happens if the value being searched for i.e. $wanted appears in a field other than the pid field ?. If I understand the suggested code correctly the whole process table (including cpu,ctime,gid etc.. ) is being searched . Hence if the value appears in cpu instead of pid then it would still flag as having found the pid . Perhaps you could comment ?

      The post you're replying to contains code that -as such- won't work. With a simple correction it would become equivalent to mine. In that case neither of them would claim having found the pid if it's not in the pid field. That's why the method is called... ehm... pid().