in reply to Re: Re: Link a hash and an array
in thread Link a hash and an array

Maybe like this (without any error checking):
our @Address=qw(type firstname lastname streetaddress city zip); our @Phone=qw(type name phonenumber); our %Types = ( "addr" => \@Address, "phone" => \@Phone ); our %Stuff; sub ReadStuff{ @Stuff{@{$Types{$_[0]}}} = @_; #...do something useful... }

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re: Re: Re: Re: Link a hash and an array
by SkipHuffman (Monk) on Mar 12, 2004 at 15:52 UTC
    @Stuff{@{$Types{$_[0]}}} = @_;

    This syntax is interesting. I have now copied it without fully understanding it. This part:

    @{$Types{$_[0]}}

    Seems to indicate, "Pull me the contents of this array element, and return it to me as an array". Am I correct?

    The outer curly braces intrige me. I am sure that I read somewhere that the syntax should be:

    @$Types{$_[0]}

    Which I tried with little success. The braced version does work, but I hate to do things by magic. What do they mean?

    Again, Thank you,

    Skip

      Sorry, I should have broken it down for you.

      @Stuff{@{$Types{$_[0]}}} = @_;
      Working from the inside out. $_[0] is the 0th element of @_. If its value is "addr", then the value of $Types{"addr"} is \@Address (a reference to the global @Address).

      @{\@Address} takes the reference and "returns" the array it points to. @Stuff{@Address}, known as a "hash slice", is assigned the values in the @_ array, and is equivalent to this:

      @Stuff{@Address} = qw(addr bob smith '1234 main st' anytown 20500);
      A hash slice is just shorthand for this:
      $Stuff{type} = 'addr'; $Stuff{firstname} = 'bob'; ... $Stuff{zip} = '20500';

      [I hope that was clear]

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

        Thank you for breaking that down. That is what I thought you meant.

        I sometimes give the impression that I have more of a clue than I do. Often I have beaten on some narrow area that I can talk intellegently about it, but look like an absolute fool when talking about something closely related. I am learning perl. I will get there.

        Skip