in reply to search an array

If you're going to be looking up spids frequently, then yes, you may want to use a hash. Something like the following (untested) code is what you want:
my $xpid = 1234; %procs = map {$_ => 0} @{$dbh->selectall_arrayref( "select spid from v\$process")}; if (defined($procs{$xpid})) { print "Pid is in use : $xpid\n"; }
--roboticus

Replies are listed 'Best First'.
Re^2: search an array
by jwkrahn (Abbot) on May 26, 2006 at 11:34 UTC
    You are assigning the value 0 to every key so every key will be defined however you can't test for truth because 0 is false. If instead of assigning 0 you assigned any non-zero value you wouldn't have to use defined() to test the keys:
    my $xpid = 1234; %procs = map { $_ => 1 } @{ $dbh->selectall_arrayref( "select spid fro +m v\$process" ) }; if ( $procs{ $xpid } ) { print "Pid is in use : $xpid\n"; }
    Another way to do it:
    my $xpid = 1234; @procs{ @{ $dbh->selectall_arrayref( "select spid from v\$process" ) } + } = (); if ( exists $procs{ $xpid } ) { print "Pid is in use : $xpid\n"; }
      jwkrahn:

      Thanks, I hadn't thought of that. It certainly simplifies things a bit!

      I'm not a perl golfer yet, but I think you just got a birdie! 8^)

      --roboticus

      Out of curiousity I tried testing these out and neither seem to work ?
      use DBI; use DBD::Oracle; $dsn = "dbi:Oracle:MYSID"; $dbuser = "myuser/mypass"; my $dbh = DBI->connect($dsn, $dbuser, '', { AutoCommit => 1, PrintErro +r => 0 }); unless($dbh) { die "Unable to connect ($DBI::errstr)\n"; exit 1; } @procs{ @{ $dbh->selectall_arrayref( "select spid from v\$process" ) } + } = (); my $xpid = 16405; if ( exists $procs{ $xpid } ) { print "Pid in use : $xpid\n"; }
      The $xpid definitely exists in the v$process view. Is there something missing from this ?