develooper Front page | perl.beginners | Postings from August 2009

Re: Creating array variable names on the fly

Thread Previous
From:
Steve Bertrand
Date:
August 28, 2009 06:05
Subject:
Re: Creating array variable names on the fly
Message ID:
4A97D61F.1060300@ibctech.ca
ANJAN PURKAYASTHA wrote:
> Hi,
> I have a question on creating array variables.  I have a driver script that
> takes as input the number of files to be processed (say 7).  One of the
> children scripts needs to create array variables based on how many files are
> being processed (in this case 7).  How do I code the following action into
> the child script: read the number of files to be processed. based on this
> number create a set of arrays say @array1, @array2....@array7"?

Very quick and dirty, and mostly to test autoviv. My first thought was
to create an array that houses a dynamic number of anonymous arrays as
it's elements. It assumes that you will be passing in the number of
files as a parameter to a function.

Although the code works, it undoubtedly sucks, and there are far better
ways to do it :)

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my @hierarchy = create_arrays( 7 );

$hierarchy[5][3] = "This is array 6, slot 4";

print Dumper \@hierarchy;

sub create_arrays {

    my ( $number_of_files ) = @_;

    my @top_level;

    for (1..$number_of_files) {
        push @top_level, [];
    }

    return @top_level;
}


__END__

prints:

dump % ./create_arrays.pl
$VAR1 = [
          [],
          [],
          [],
          [],
          [],
          [
            undef,
            undef,
            undef,
            'This is array 6, slot 4'
          ],
          []
        ];


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About