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

#!/usr/bin/perl my %hash = {'hello' => 'world', 'says' => 'just another perl hacker'}; my $hashref = \%hash;
i want to how to display keys/values or what every using $hasref. assume i know only hashref and don't know anything about %hash can u please give the sample example plz

Retitled by davido from 'hashref'.

Replies are listed 'Best First'.
Re: How to access contents of a reference to a hash.
by ambrus (Abbot) on Jan 31, 2005 at 12:36 UTC

    The way you initialize the hash is wrong. Add use warnings; use diagnostics; to the top of your script to see why.

      thanks a lot it's really helpfull
      perl -> 'hacker"' hello -> 'world,' says -> '=>' "just -> 'another'
      but i want some thing like this
      hello -> 'world,' says ->just another perl hacker
        i got it
        #!/usr/bin/perl use warnings; use diagnostics; my %hash = ('hello' => 'world', 'says' => 'just another perl hacker'); my $hashref = \%hash; foreach my $k (keys %$hashref) { print "$k -> '$hashref->{$k}'\n " }
        Thanks a lot guys
Re: How to access contents of a reference to a hash.
by Corion (Patriarch) on Jan 31, 2005 at 12:31 UTC

    There is the easy way:

    print $hashref->{hello};

    That easy way is not enough if you need something like the "original hash" %hash:

    print join "\n", sort keys %{$hashref};

    Most likely, tyes References quick reference will be of help when you're dealing with references.

    Update: As ambrus points out, I didn't read your code close enough - you are initializing the hash wrong. Assign a list to the hash, not a hash reference:

    my %hash = ( hello => 'world', foo => 'bar', );
Re: How to access contents of a reference to a hash.
by borisz (Canon) on Jan 31, 2005 at 12:33 UTC
    Look at each and keys. If you just want to look at the content, Data::Dumper is a fine choice.
    use Data::Dumper; print Dumper($hashref);
    Boris
Re: How to access contents of a reference to a hash.
by DaleCooper (Initiate) on Feb 01, 2005 at 13:53 UTC
    This requires the De reference operator use what you find at the end of reference, in Perl you use '->'
    #!/usr/bin/perl my %hash = {'hello' => 'world', 'says' => 'just another perl hacker'}; my $hashref = \%hash; print "$hashref->{'says'} in the $hash{'world'}\n" ;
    Will return:
    just another perl hacker in the world