Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Foreach through Multidimensional Array?

I have a script that takes pathnames/files that are too old (as decided via user input) and deletes them. I want to list each directory separately and ask for confirmation of deleting the old files in each directory.

So, I have an array (@oldDirs) that holds multiple arrays (each directory), which hold strings (the fullpath names).

@oldDirs = (@AirDefense,@Arcsight,@Avocent,@BlueCoat,@Checkpoint,@Cisco,@Crossbeam,@FireE ye,@lostAndFound,@rancid,@Riverbed,@Symantec,@Wiki,@WLAN)

if($oldPathsSize != 0)
{
    my $dirNamesCounter = 0;
    my @dirNames =     ('/AirDefense','/Arcsight','/Avocent','/BlueCoat','/Checkpoint','/Cisco','Crossbeam','FireE ye','/lost+found','/rancid-2.3.8','/Riverbed','/Symantec','/Wiki','/WLAN');
    foreach my @direc (@oldDirs)
    {
        my $size = @direc;
        print "Confirm Deletion of $size Old files in $dirNames[$dirNamesC]: \n";
        $dirNamesCounter++;

        foreach my $pathname (@direc)
        {
            print "\t$pathname\n";
        }

        print "\nDelete All?(y/n): ";
        my $delete = <STDIN>;
        chomp($delete);

        if($delete eq "y")
        {
           #delete file
        }
    }
}

My issue is with the first foreach statement. Both are arrays and @direc isn't allowed because I need to have a scalar value in that part of the foreach...but they're all arrays! How am I supposed to do this, if it's even possible?

like image 582
geeoph Avatar asked Jun 05 '13 20:06

geeoph


1 Answers

You should read perllol - Manipulating Arrays of Arrays in Perl. You cannot create a multidimensional array like this:

my @array1 = (1, 2, 3);
my @array2 = qw/a b c/;
my @multi  = (@array1, @array2);

Instead, the arrays will be flattened and @multi will contain

1, 2, 3, 'a', 'b', 'c'

You have to use references:

my @multi = (\@array1, \@array2);
for my $ref (@multi) {
    for my $inner (@$ref) {
        # ...
    }
}
like image 118
choroba Avatar answered Nov 08 '22 17:11

choroba