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

Hi people, I am having a little trouble getting this beauty to work :

trying to write a simple/good data loader for generic CSV files, I came up with this idea to specifically do it with symbolic links

I explain :

@test=(11,22,33,44); @Fld=('LCD','XCOORD','Y','Name'); @Data{@Fld}= @test; print "Y($Data{'Y'}) N($Data{'LCD'})\n"; # until here all works fine ${$Fld[2]}=$test[2]; # <--- works ${$Fld[3]}=$test[3]; # <--- works ${@Fld}=@test; # <--- does NOT work, why ?! print "Y($Y) N($Name)\n";

thx in advance for any suggestion

kind regards

jc

Replies are listed 'Best First'.
Re: symbolic reference & loading hashes
by ikegami (Patriarch) on Jul 20, 2007 at 16:07 UTC

    ( Update: Oh! you are trying to create symbolic reference. Read Why it's stupid to `use a variable as a variable name' for why that's unwise. Use a hash instead, and then you can use the hash slice I mention below. )

    I don't know what you are trying to do, but I'll point out two problems with that statement.

    • You are assigning an array to a scalar.

      ${@Fld}=@test; ^ ^ | | scalar array

      An array evaluated in scalar context returns its length, so the length of the array would be assigned.

    • ${@Fld} doesn't make much sense. It looks like a dereference, but @Fld is not a reference. Since references are scalars, the dereference (${...}) expects a scalar value. @Fld evaluated in scalar context is its length, so ${@Fld} is ${2} aka $2.

    Maybe you are looking for a hash slice?

    my @test=(11,22,33,44); my %Fld; @Fld{'LCD','XCOORD','Y','Name'} = @test; print($Fld{Y}, "\n"); # prints 33
Re: symbolic reference & loading hashes
by neosamuri (Friar) on Jul 20, 2007 at 16:01 UTC

    I believe what you are looking for is:

    @{@keys} = @values;

    ${...} is scalar, but the return you want is an array @rld is the keys in the package hash. @{...} takes keys and returns values. ${...} takes a key and returns a value.

      Nope, that will evaluate @keys in scalar context in order to deref the value. Perl doesn't provide any direct means of setting multiple referenced values at once, so a loop is needed.

      for my $i (0..$#keys) { ${$keys[$i]} = $values[$i]; }

      Alternatively,

      use List::MoreUtils qw( pairwise ); pairwise { ${$a} = $b } @keys, @values;

      Of course, hashes are better than symbolic references.

      @hash{@keys} = @values;