Beefy Boxes and Bandwidth Generously Provided by pair Networks Ovid
laziness, impatience, and hubris
 
PerlMonks  

Re^3: Creating a unique variable type

by topher (Scribe)
on Mar 25, 2013 at 23:21 UTC ( #1025411=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Creating a unique variable type
in thread Creating a unique variable type

Technically, you are correct. An array value can only hold a scalar variable.

However, there are a couple of ways you can work around that. The most common is references. Instead of storing an array inside of another array, you store array references (which are scalar values) in your array.

The easiest way would be an array of array references:

my @array = ( "a", "b", "c" ); my $aref = [ "x", "y", "z" ]; push @array, $aref; # Current value for @array: #@array = ( # "a", # "b", # "c", # [ # "x", # "y", # "z" # ], # )

A brief example of using an array of array references:

#!/usr/bin/env perl use strict; use warnings; my @array; while (<DATA>) { chomp; my ($bool,$int) = split ","; # Take each ($bool,$int) tuple, and store it in an array reference # (By placing it in []) that we add to our array push @array, [ $bool, $int ]; } # Cycle through our array of array references and print them foreach my $entry (@array) { print "Bool: " . $entry->[0] . "\n"; # The -> dereferences our ar +rayref print "Int: " . $entry->[1] . "\n\n"; # The -> dereferences our ar +rayref } __DATA__ 0,14 0,7 1,13 0,3 1,9 0,2 1,1

Giving us the following output:

perl-fu@nexus:~/foo$ ./a_of_a.pl Bool: 0 Int: 14 Bool: 0 Int: 7 Bool: 1 Int: 13 Bool: 0 Int: 3 Bool: 1 Int: 9 Bool: 0 Int: 2 Bool: 1 Int: 1

For more information on nested data structures using references, you should check out perlreftut and perlref.

Christopher Cashell


Comment on Re^3: Creating a unique variable type
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2014-04-21 08:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (492 votes), past polls