in reply to Re^2: Getting Getopt::Long values into a hash
in thread Getting Getopt::Long values into a hash

It seems that you must have $my_hash as a hashref, rather than having a %my_hash. The arrow-form adds a dereference to the LHS value. In my example, #1 and #2 are equivalent:

my $ref = { foo => "bar" }; print ${$ref}{"foo"}; #1 prints "bar" print $ref->{"foo"}; #2 prints "bar" print $ref{"foo"}; #3 prints "" # and under strictures throws a: # "Global symbol "%ref" requires explicit package name"

$ref{"foo"} only returns a value if there is a hash named %ref.

Replies are listed 'Best First'.
Re^4: Getting Getopt::Long values into a hash
by jeanluca (Deacon) on Nov 08, 2005 at 15:21 UTC
    I almost start my script with: my $my_hash = {} ; As far as I know this should create a hash reference ?!
    What exactly means 'dereference to the LHS value' ?
    When it comes to variables and references I often get confused!

    Thnx
    Luca
      As far as I know this should create a hash reference

      Yes that is correct.

      What exactly means 'dereference to the LHS value'?

      LHS = left hand side. I meant that the arrow operator takes a reference on the left, and dereferences it (ie. 'replaces' it with what it points to). You can then subscript it in various ways, with a key (for a hashref), an index (arrayref), parameters (coderef), or a method (object).

      A hashref is not a hash, and thus you cannot access it directly. You need to first "fetch" the hash that it points to.

        Thanks a lot, I just wrote a short test program:
        #! /usr/bin/perl my %mh ; $mh{a} = "b" ; $mh->{b} = "c" ; print "values are hash=$mh{a}, hash=$mh{b} or hashref=$mh->{b} \n" ;
        The problem with perl I think is that different types can have the same name.
        I wrote a script once, and before I knew it I was mixing hashes and hash references!

        Luca