Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

In reply to Re^3: Creating a unique variable type by topher
in thread Creating a unique variable type by tfredett

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-03-28 11:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found