in reply to search an array

You seem to be misunderstanding how grep works. I recommend re-reading the documentation.

You actually want something like this:

if ( grep $_ == $xpid, @procs ) { print "Pid is in use : $xpid\n"; }

Also, fetchrow_arrayref returns an array _reference_ (as in the name). So you should be writing:

$procs = $dbh->selectall_arrayref("select spid from v\$process"); if ( grep $_ == $xpid, @$procs ) { print "Pid is in use : $xpid\n"; }

The potential downside with grep is that it always searches the whole list - which will impact performance if the list is large. Something like this might be more efficient (or build a hash as robiticus suggests):

$procs = $dbh->selectall_arrayref("select spid from v\$process"); my $found; foreach (@$procs) { if ($_ == $xpid) { $found = 1; last; } } if ($found) { print "Pid is in use : $xpid\n"; }

Oh, and one last tip. If you use single quotes around your SQL then you don't need to escape the '$'.

$procs = $dbh->selectall_arrayref('select spid from v$process');
--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: search an array
by Anonymous Monk on May 26, 2006 at 12:49 UTC
    Given the number of times I need to do this I've decided to go down the hash route . However thanks for your answer, it's shown me some things I hadn't considered (even after reading the manual).
    One thing I'd like to add is that the " around the SQL statement is purely habit on my part.
    I often have to write SQL that does something like this
    "select blah from v\$someview where upper(NAME) like upper('%file%')"
    Hence the need to use double instead of single quotes
Re^2: search an array
by Anonymous Monk on May 26, 2006 at 15:04 UTC
    I can't seem to get this to work. I thought I'd try this out to compare it for speed with the hash version mentioned later. It never prints the pid in use message even though the pid exists in the array. How do I debug this statement
    if ($_ == $xpid) {
    To see why the match is not being made ? I tried
    print @$_ ;
    This gives me the value I expect to see (i.e. a pid) but even though $xpid appears to have the same value the if is not evaluating to true ?
      I've answered my own question. The answer I found is
      if ("@$_" == "$xpid") {
      Sorry for the confusion