Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Soft Array Refs

by stevieb (Canon)
on Jun 23, 2015 at 22:45 UTC ( [id://1131746]=note: print w/replies, xml ) Need Help??


in reply to Soft Array Refs

Don't do it. Here's a valuable and entertaining three part story by Mark-Jason Dominus as to why doing these things should be avoided wherever possible. There are many other stories out there stating why this isn't such a good idea unless you *really* know what you're doing.

Hashes are designed for this. Here's an example. Just ask if you have questions. Usually, it's the dereferencing that confuses most people.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %data; my $array_name; while (my $line = <DATA>) { chomp($line); if ($line =~ /Array\s+(\w+)\s+(\d+)/) { $array_name = "table_" . $1 . "_" . $2; next; } my $value = (split /\s+/, $line)[1]; push @{ $data{$array_name} }, $value; } print "Printing entire structure:\n"; print Dumper \%data; print "\nPrinting all values from all arrays:\n\n"; for my $key (keys %data){ print "in array '$key'\n"; for my $elem (@{ $data{$key} }){ print "$elem\n"; } } print "\nPrinting values only from 'table_min_1':\n"; for my $item (@{ $data{'table_min_1'} }){ print "$item\n"; } __DATA__ Array max 1 useless_text_field a useless_text_field b useless_text_field c Array max 2 useless_text_field 1 useless_text_field 2 useless_text_field 3 Array min 1 useless_text_field d useless_text_field e useless_text_field f Array min 2 useless_text_field 4 useless_text_field 5 useless_text_field 6

-stevieb

Replies are listed 'Best First'.
Re^2: Soft Array Refs
by smknjoe (Beadle) on Jun 24, 2015 at 02:50 UTC

    Thanks Stevie.

    I regretted posting it about 30 minutes later after I had two words for myself: "associative arrays", aka a hash.

    Up to now, I've gotten by with arrays for everything but now I see a true need for using a hash.

      Rule of thumb: If order matters, use an array; otherwise use a hash.

      Most of the time, you should use a hash because of its expressive power. You can think of a hash as a miniature symbol table, if it helps. :)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2024-04-18 10:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found