Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

pushing an anonymous hash onto an array on the fly

by owenmann (Initiate)
on Feb 22, 2013 at 22:39 UTC ( [id://1020242]=perlquestion: print w/replies, xml ) Need Help??

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

Hi all, first-time poster, mediocre Perl programmer.
I'm taking in a "|"-delimited file with predefined columns and want to turn it into an AoH for sorting. This works fine:
foreach (@array) { @hash{qw<source_id exchange_id status exchange desc depth_flag dep +th_indic>} = split /\|/; push @AoH, {%hash}; };
I want to combine the two lines down to one, like this:
foreach (@array) { push @AoH, { @{ qw<source_id exchange_id status exchange desc dept +h_flag depth_indic> } = split /\|/} ; };
...but I get the error:
Can't modify anonymous hash ({}) in list assignment at /home/omann/exch_list.pl line 66, near "/\|/;"
Is this possible?

Replies are listed 'Best First'.
Re: pushing an anonymous hash onto an array on the fly
by SuicideJunkie (Vicar) on Feb 22, 2013 at 22:53 UTC

    I don't see the point of making it one line, but sure you can do it:

    use strict; use warnings; use List::MoreUtils qw(mesh); use Data::Dumper; my @array = ('source|ex|stat|ex2|desc|dep|ind'); my @columns = qw<source_id exchange_id status exchange desc depth_flag + depth_indic>; my @AoH; foreach (@array) { push @AoH, { mesh(@columns, @{[split /\|/,(shift @array)]}) } ; }; print Dumper @AoH;
    Gives:
    C:\>perl test.pl $VAR1 = { 'source_id' => 'source', 'desc' => 'desc', 'status' => 'stat', 'depth_indic' => 'ind', 'depth_flag' => 'dep', 'exchange_id' => 'ex', 'exchange' => 'ex2' }; C:\>
Re: pushing an anonymous hash onto an array on the fly
by choroba (Cardinal) on Feb 22, 2013 at 22:52 UTC
    I am not sure it is quite readable, but it works:
    @{ $AoH[@AoH] }{ qw<source_id exchange_id status exchange desc depth_f +lag depth_indic> } = split /\|/;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-23 07:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found