Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


In reply to Re: assign an array into hash by johngg
in thread assign an array into hash by aakikce

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-18 23:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found