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

I decided to have hash references instead of scalars in some hashed data structure, but for backwards compatibility I also have to be able to accept scalars. What is the recommended way to find out whether a hash key points to a scalar or a hash reference?
# old structure my $hash={ key1=>'comment1', key2=>'comment2' }; # new structure my $hash={ key1=>'comment1', key2=>'comment2', key3=>{ comment=>'comment3', advice=>'advice3' }, key4=>{ comment=>'comment4', advice=>'advice4' } };
  • Comment on What is the safest way to find out whether a hash key points to a scalar or a hash reference?
  • Download Code

Replies are listed 'Best First'.
Re: What is the safest way to find out whether a hash key points to a scalar or a hash reference?
by davis (Vicar) on Feb 06, 2015 at 15:25 UTC
    Try looking at the documentation for the ref function:
    #!/usr/bin/perl use warnings; use strict; my %input_data = ( foo => { data => "cheese", }, bar => "scalar", ); foreach my $key (keys(%input_data)) { unless(ref($input_data{$key})) { print "$key isn't a reference, it's just a scalar\n"; } if(ref($input_data{$key}) eq "HASH") { print "$key is a hashref\n"; } elsif(ref($input_data{$key}) eq "SCALAR") { print "$key is a scalar ref\n"; } }

    davis

Re: What is the safest way to find out whether a hash key points to a scalar or a hash reference?
by Happy-the-monk (Canon) on Feb 06, 2015 at 15:23 UTC

    What is the recommended way to find out whether a hash key points to a scalar or a hash reference?

    The ref function.

    Cheers, Sören

    Créateur des bugs mobiles - let loose once, run everywhere.
    (hooked on the Perl Programming language)

Re: What is the safest way to find out whether a hash key points to a scalar or a hash reference?
by LanX (Saint) on Feb 06, 2015 at 15:31 UTC