Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Two arrays into hash

by Anonymous Monk
on Jul 16, 2009 at 08:26 UTC ( [id://780595]=perlquestion: print w/replies, xml ) Need Help??

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

@array1=qw(A B C); @array2=qw(1 2 3);
How to create a hash which looks like this
%hash = ( array1=>['A','B','C'], array2=>['1','2','3'] };

Replies are listed 'Best First'.
Re: Two arrays into hash
by moritz (Cardinal) on Jul 16, 2009 at 08:29 UTC
    perlreftut describes how to construct such data structures.

    If you have problems understanding something in there, or you hit some errors while trying, feel free to ask and explain what's the problem.

Re: Two arrays into hash
by Bloodnok (Vicar) on Jul 16, 2009 at 10:31 UTC
    Methinx you could use rudimentary algebraic methods to arrive at your goal, consider:
    @array1=qw(A B C); @array2=qw(1 2 3);
    is equivalent to/can be re-written as:
    @array1=('A', 'B', 'C'); @array2=('1', '2', '3');
    Also, the requirement can be re-written as:
    %hash = ( array1=>[('A','B','C')], array2=>[('1','2','3')] };
    So, substituting for ('A','B','C') & ('1','2','3'), into the re-written required result, gives:
    %hash = ( array1=>[@array1], array2=>[@array2] };
    But, [@array] can be/usually is written as \@array, hence,
    %hash = ( array1=>\@array1, array2=>\@array2 };
    As required - also discoverable by reference to perlreftut - as moritz has previously suggested.

    A user level that continues to overstate my experience :-))
      [@array] can be/usually is written as \@array

      Careful. The two are not the same. \@array returns a reference to the existing array. [@array] creates a new (anonymous) copy of the original array and returns a reference to the copy. It's a subtle difference, but an important one.

      #!/usr/bin/perl use strict; use warnings; my @arr = (1 .. 5); my %hash = ( aref => \@arr, copy => [ @arr ], ); print "@{$hash{copy}}\n"; print "@{$hash{aref}}\n"; @arr = ('a' .. 'e'); print "@{$hash{copy}}\n"; # original values print "@{$hash{aref}}\n"; # changed values
      --

      See the Copyright notice on my home node.

      Perl training courses

        Good point, well made - I rather overlooked that didn't I ?

        Thanx davorg.

        A user level that continues to overstate my experience :-))

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://780595]
Approved by ELISHEVA
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-18 22:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found