Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How to make this code more flexible

by Marshall (Canon)
on Jul 21, 2011 at 22:44 UTC ( [id://916013]=note: print w/replies, xml ) Need Help??


in reply to How to make this code more flexible

You are doing GREAT for just starting!
First, multi-dimensional data structure consists of only references until you get to the last dimension. An ArrayOfArray is what the name says, an array of references to arrays. Earlier I think I saw a 2D structure that you built with a hash for the first dimension. That is not the usual case as you don't get easy sequential processing with a hash. But sometimes this is useful. In that case this is a HashOfArray, or hash of references to arrays.

Below is some code that makes both types and returns a reference to each one. There are no limits on the size of the AoA or HoA. I do a split to get @row from the data line. The default split is on 'space',\t\f\r\t so this also gets rid of the end of line (no need for chomp). Then I just push a reference to this row array onto the AoA and to the HoA. One line of code for each one.

Whenever your code encounters a "my" variable statement. You are guaranteed to get a "new one". Perl will reuse the space the last one used or if it can't because a reference to it is in existence, new memory will be allocated.

#!/usr/bin/perl -w use strict; use Data::Dump qw(pp); my ($arrayRef, $hashRef) = makeBothTypes(); sub makeBothTypes { my $rowName = 'A'; my @twoDarray; my %twoDhash; while (<DATA>) { my @row = split; # no chomp needed for default split push @twoDarray, \@row; $twoDhash{$rowName++} = \@row; } return (\@twoDarray,\%twoDhash); } print pp($arrayRef); print pp($hashRef); print "\n"; print "$hashRef->{B}[2]\n"; #23 print "$arrayRef->[1][2]\n"; #23 =output that this prints.... [ [11, 12, 13, 14, 15, 16, 17], [21, 22, 23, 24, 25, 26, 27], [31, 32, 33, 34, 35, 36, 37], [41, 42, 43, 44, 45, 46, 47], [51, 52, 53, 54, 55, 56, 57], ]{ A => [11, 12, 13, 14, 15, 16, 17], B => [21, 22, 23, 24, 25, 26, 27], C => [31, 32, 33, 34, 35, 36, 37], D => [41, 42, 43, 44, 45, 46, 47], E => [51, 52, 53, 54, 55, 56, 57], } 23 23 =cut __DATA__ 11 12 13 14 15 16 17 21 22 23 24 25 26 27 31 32 33 34 35 36 37 41 42 43 44 45 46 47 51 52 53 54 55 56 57

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-19 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found