in reply to Re: Is there a cleaner way to write this code below, which includes derferencing references, that themselves have to be dereferenced?
in thread Is there a cleaner way to write this code below, which includes derferencing references, that themselves have to be dereferenced?

Thank you for this:

@GenericData{@ticketsFields} = @$rows;

It works great, just would like to understand it.

Why isn't it?
   %GenericData{@ticketsFields} = @$rows;

Since I am building a hash, I would have just assumed the above. Just want to understand why it's being called as an array instead of a hash.

Thanks again

  • Comment on Re^2: Is there a cleaner way to write this code below, which includes derferencing references, that themselves have to be dereferenced?
  • Download Code

Replies are listed 'Best First'.
Re^3: Is there a cleaner way to write this code below, which includes derferencing references, that themselves have to be dereferenced?
by GrandFather (Saint) on May 05, 2022 at 21:58 UTC

    $, % and @ are sigils. They denote the type of thing being returned from an expression. They are not the type of a variable. So $rows is a variable ('rows') returning a scalar value. @$rows is a scalar variable deferenced to return an array.

    You can index into a hash variable (%GenericData for example) to get a scalar value - the value associated with the key that was used: my $value = $GenericData{key};. 'GenericData' in that case is the hash variable, but the indexing expression returns a scalar value.

    Perl also lets you slice hashes and arrays. In that case an array of values is returned so regardless of it being an array slice or a hash slice @ is used to show an array being returned: my @values = @GenericData{@ticketsFields}. An interesting and useful wrinkle is that you can then assign an array to the slice. Consider the following example which reverses the order of values associated with keys in a hash using assignment between hash slices:

    use strict; use warnings; my %hash = (one => 1, two => 2, three => 3); my @keys = sort {$hash{$a} <=> $hash{$b}} keys %hash; print "$_ => $hash{$_} " for @keys; print "\n"; @hash{@keys} = @hash{reverse @keys}; print "$_ => $hash{$_} " for @keys;

    Prints:

    one => 1 two => 2 three => 3 one => 3 two => 2 three => 1
    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond