Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Perl: Forming array from scalar value ?

Options
  • 04-08-2004 2:28pm
    #1
    Closed Accounts Posts: 913 ✭✭✭


    Hi guys,

    I'm trying to form a new array, the name of which is
    based on the value of a scalar.
    But perl don't like it:

    @array_$i = ();

    This will be in a loop with $i incrementing.

    What I want is:

    @array_1 = ();
    @array_2 = ();
    @array_3 = ();...etc

    Any ideas ?

    TIA
    R


Comments

  • Registered Users Posts: 1,023 ✭✭✭[CrimsonGhost]


    A variable-variable.
    I've used them in php, you'd some thing like

    $varstr = "array_";
    $counter = 1;

    $newvar = $varstr . $counter;

    $$newvar = "what ever the hell you want";

    If you can use variable variables in perl it'd probably be something similar. You'd have the above some loop incrementing $counter.

    A quick google for perl "variable variables" turned up
    www.programmersheaven.com/ zone27/articles/article535.htm
    and
    www.tek-tips.com/gviewthread.cfm/pid/219/qid/868000
    One of which may be some use.


  • Closed Accounts Posts: 304 ✭✭Zaltais


    #!/usr/bin/perl -w
    use strict;
    
    my $array;
    
    my $i = 0;
    
    while ($i < 10){
    	$array->[$i] = (["a", "b", "c"]);
    	$i++
    }
    
    print $array->[5]->[1];
    

    Very simple example, but this creates a 'grid'.
    Grid has 10 rows (0 to 9) and 3 columns (0 to 2).
    Final line print's the second column of the sixth row.

    Naturally you can use variables to refer to any particular 'cell' of the 'grid'.
    So given the above code followed by:
    my $y = 3;
    my $x = 0;
    
    print $array->[$y]->[$x];
    

    We get the first column of the fourth row.

    Bit of a headmelter to get your head round, especially given such a simple example, but take a look at 'perllol' (Manipulating Arrays of Arrays in Perl) 'perlreftut' (Perl References Tutorial) and 'perldsc' (Perl Data Structures Cookbook) - or go here and here and here.

    You can also create hashes of arrays, arrays of hashes, hashes of arrays of hashes, etc., etc.

    Feel free to post back with any questions.


  • Closed Accounts Posts: 913 ✭✭✭HarryD


    problem solved.. Thanks Guys :-)


Advertisement