Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Seeing if a hash has one arbitrary key

by grinder (Bishop)
on Feb 13, 2003 at 17:39 UTC ( #235037=snippet: print w/ replies, xml ) Need Help??

Description:

I have some data scrubbing to do, and to divide and conquer the problem, I decided to fix the easy things first, so that I can work in peace on the trickier stuff.

In essence, I have a hash of hashes that represent the count of attributes seen for a collection of things. Sometimes I see the same attribute more than once, sometimes I see many attributes once, and any combination in between.

Most of the things, though, have one attribute, seen once. I therefore wanted to go throught the hash and put them to one side, and put what remains on the other. The trouble is, that solitary attribute has an abitrary name, so I can't just see if it exists. After futzing around a while and getting nowhere fast and more and more complicated, the following suddenly popped out at me.

Note that the $h{key}{subkey} stuff below is actually coming from something like:

while( <> ) { chomp; my( $key, $subkey ) = split; $h{$key}{$subkey}++; }

(It's the $h{$c}{(keys %{$h{$c}})[0]} == 1 bit that pleases me).

#! /usr/bin/perl -w

use strict;

my %h;

# two different subkeys
$h{foo}{bar}++;
$h{foo}{rat}++;

# one subkey
$h{fob}{rat}++;

# one subkey seen more than once
$h{fod}{car}++;
$h{fod}{car}++;

for my $c( keys %h ) {
    if( scalar keys %{$h{$c}} == 1 and $h{$c}{(keys %{$h{$c}})[0]} == 
+1 ) {
        print "$c has a ${\(keys %{$h{$c}})[0]}\n";
    }
    else {
        print "$c is complicated\n";               
    }
}
Comment on Seeing if a hash has one arbitrary key
Download Code
Re: Seeing if a hash has one arbitrary key
by jdporter (Canon) on Feb 13, 2003 at 18:01 UTC
    That looks complicated (though it isn't really).
    I'd probably use a temporary:
    for my $c ( keys %h ) { my @attr = keys %{$h{$c}}; if ( @attr == 1 and $h{$c}{$attr[0]} == 1 ) { print "$c has a $attr[0]\n"; } . . .

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

Re: Seeing if a hash has one arbitrary key
by Aristotle (Chancellor) on Feb 19, 2003 at 01:15 UTC
    my @subvalues = values %{$h{$c}}; print "complicated" unless @subvalues == 1 and $subvalues[0] == 1;

    Makeshifts last the longest.

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://235037]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (18)
As of 2014-09-22 14:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (195 votes), past polls