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

I have created a hash ref ($prop_ref) for %prop. How do I find a length of the hash elements using hash reference.

Replies are listed 'Best First'.
Re: How to find length of $hash_ref
by kennethk (Abbot) on May 04, 2009 at 22:51 UTC
    I assume by "a length of the hash elements" you mean the number of elements in the hash referenced. This is a faq. Since you are dealing with a reference, the code would be:

     my $num_keys = keys %$prop_ref;

    If you instead want to determine string lengths of keys or values, you can use length.

      Yes I meant number of elements only. Thanks
        Pretty simple when you dereference it eh? I'm told (and hopefully not being lied to!) that pretty much the only way to get at anything about the referenced value (besides, say, the position in the memory. Soooooo useful!) is to dereference.
Re: How to find length of $hash_ref
by bichonfrise74 (Vicar) on May 05, 2009 at 01:10 UTC
    Consider this example...
    #!/usr/bin/perl use strict; my %prop = ( "abc" => "100", "def" => "22" ); my $prop_ref = \%prop; print map { "$_ has " . length($$prop_ref{$_}) . " characters.\n" } sort keys %{$prop_ref};
Re: How to find length of $hash_ref
by vinoth.ree (Monsignor) on May 05, 2009 at 03:51 UTC

    Try to find the number of elements in the hash by dereference the hash reference

    use strict; use warnings; my %hash=(key1=>'value1',key2=>'value2',key3=>'value4'); my $hash_ref=\%hash; print scalar keys %$hash_ref;
    Vinoth,G