Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: assign an array into hash

by johngg (Canon)
on Apr 26, 2007 at 09:37 UTC ( [id://612171]=note: print w/replies, xml ) Need Help??


in reply to assign an array into hash

There are a few problems with your code. Firstly, it is always recommended to place use strict; and use warnings; at the top of your scripts to help avoid typos etc.

When you read your file you construct an array with one element per line where you actually need two. Interpolating an array into a string is only going to result in a single string being assigned to your hash. In any case, qw( ... ) doesn't interpolate so you were assigning the string "@con" to your hash. You can assign an array to a hash but you will get a warning if there aren't an even number of elements..

use strict; use warnings; use Data::Dumper; my $inFile = q{spw612167.dat}; open my $inFH, q{<}, $inFile or die qq{open: $inFile: $!\n}; my @conArr = (); while ( <$inFH> ) { chomp; push @conArr, split m{=>}; } close $inFH or die qq{close: $inFile: $!\n}; my %conHash = @conArr; print Data::Dumper->Dump([\@conArr, \%conHash], [qw{*conArr *conHash}] +);

Here's the output

@conArr = ( 'article', 'art', 'chapter', 'chap', 'section', 'sec' ); %conHash = ( 'chapter' => 'chap', 'article' => 'art', 'section' => 'sec' );

I hope this helps you.

Cheers,

JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (8)
As of 2024-03-28 11:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found