Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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$ ./ 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

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2016-10-23 15:01 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (301 votes). Check out past polls.