Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Does inner hash/key exist?

by blink (Scribe)
on May 31, 2003 at 13:47 UTC ( [id://262065]=perlquestion: print w/replies, xml ) Need Help??

blink has asked for the wisdom of the Perl Monks concerning the following question:

Given the following code, how could I effectively test for the existance of (@{$failed{$client}}, $sid) before populating it? I'm not sure how to use 'exist' in the context of a nested data structure.
foreach my $key (sort keys %jobs) { my $job = $jobs{$key}->{jobid}; my $status = $jobs{$key}->{status}; my $client = $jobs{$key}->{client}; my $class = $jobs{$key}->{class}; my $files = $jobs{$key}->{files}; if ($status gt 0 && $status ne 150) { my ($host, $sid, $type) = split ('_', $class); if ($type =~ /hot|cold/) { push (@{$failed{$client}}, $sid); } else { push (@{$failed{$client}}, $files); } } }

Replies are listed 'Best First'.
Re: Does inner hash/key exist?
by pfaut (Priest) on May 31, 2003 at 13:55 UTC

    grep?

    push @{$failed{$client}}, $sid unless grep $_ eq $sid, @{$failed{$clie +nt}};
    90% of every Perl application is already written.
    dragonchild
      Perfect! Thanks!
Re: Does inner hash/key exist?
by Aristotle (Chancellor) on May 31, 2003 at 14:04 UTC
    pfaut answered your question, I'd just like to add some minor advice: you can remove redundancy in your assignments block by using a hash slice.
    my ($job, $status, $client, $class, $files) = @{$jobs{$key}}{qw(jobid status client class files)};

    Makeshifts last the longest.

Re: Does inner hash/key exist?
by runrig (Abbot) on May 31, 2003 at 15:05 UTC
    pfaut already answered your question, but when you have to grep through arrays to determine existance, you almost always should be using a hash and the exists function. Even if you need to keep them in the order that they were found, you can use your array in conjunction with a separate hash (or hash of hashes in your case):
    push {@{$failed{$client}}, $sid unless exists $fail{$client}{$sid}; $fail{$client}{$sid} = undef;
    Or just do the second statement if you don't need to keep the keys in order, then it doesn't matter if it exists already.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://262065]
Approved by Aristotle
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-25 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found