whit3y
whit3y

Reputation: 65

I'm trying to take a file and break it into seperate arrays perl

as the title says, I have a simple text file and I'm trying to break it up into several different arrays. Here is what the simple text file will look like

--ARRAY1--
eenie
--ARRAY2--
meenie
minie
--ARRAY3--
moe

the big idea that I had in my code will loop through this file and place everything between the "--Arrays--" into arrays that correspond to what array it is in the text file.

##logic that loops through above text file{

$line =~ s/[\ ]//g; #chops off spaces
        if($line =~/(\-\-)/){
                if($line =~/[ARRAY1]/){$arrayholder='array1';}
                if($line =~/[ARRAY2]/){$arrayholder='array2';}
                if($line =~/[ARRAY3]/){$arrayholder='array3';}
        }
push @"$arrayholder", "$line";
}

## END LOOP LOGIC}

The problem I'm having is with

push @"$arrayholder", "$line";

It seems I cant use a variable to call on an array. I even tried doing

if($line =~/[ARRAY2]/){$arrayholder='@array2';}

to no avail

Any help is appreciated. I'm open to fixing my entire logic. Thanks

Upvotes: 0

Views: 74

Answers (2)

Borodin
Borodin

Reputation: 126742

If I understand you correctly then I suggest you use a hash of array references. Like this

use strict;
use warnings;

my %data;
my $array;

while (<DATA>) {
  chomp;
  if (/^--(\w+)--/) {
    $array = $1;
  }
  elsif ($array) {
    push @{ $data{$array} }, $_;
  }
}

use Data::Dump;
dd \%data;

__DATA__
--ARRAY1--
eenie
--ARRAY2--
meenie
minie
--ARRAY3--
moe

output

{ ARRAY1 => ["eenie"], ARRAY2 => ["meenie", "minie"], ARRAY3 => ["moe"] }

Upvotes: 2

toolic
toolic

Reputation: 62164

Consider a hash-of-arrays data structure:

use warnings;
use strict;

my %hoa;
my $arr;
while (<DATA>) {
    chomp;
    if (/^--(\w+)/) {
        $arr = $1;
        next;
    }
    else {
        push @{ $hoa{$arr} }, $_;
    }
}

use Data::Dumper;
$Data::Dumper::Sortkeys=1;
print Dumper(\%hoa);

__DATA__
--ARRAY1--
eenie
--ARRAY2--
meenie
minie
--ARRAY3--
moe

This prints out:

$VAR1 = {
          'ARRAY1' => [
                        'eenie'
                      ],
          'ARRAY2' => [
                        'meenie',
                        'minie'
                      ],
          'ARRAY3' => [
                        'moe'
                      ]
        };

Upvotes: 1

Related Questions