klgabs
klgabs

Reputation: 85

my output array to merge into just one array

My sample code to display the lists of directory listed in source_dir_ref.txt but I need to merge it to one array

#! /usr/bin/env perl
use feature qw(say);
use strict;
use warnings;

use Data::Dumper;
use Getopt::Long;

my $infile = 'source_dir_ref.txt';
my $file = $ARGV[0];

GetOptions ("infile=s" => \$file ) or die("Error in command line arguments\n");

open(DATA, $infile) or die "Couldn't open file $file";

while(my $line = <DATA>) {
         chomp($line);
         #say "$line";
         my @listdir = $line;
         say Dumper \@listdir;

}

My result after running my code

$VAR1 = [
          '/archives/data/mefab/STAGING/PRODUCTION'
        ];

$VAR1 = [
          '/archives/data/bkfb/STAGING/PRODUCTION'
        ];

$VAR1 = [
          '/archives/data/szast/STAGING/PRODUCTION'
        ];

$VAR1 = [
          '/archives/data/cpast/STAGING/PRODUCTION'
        ];

My objective is to merge this array to just one array.

@sourcedirs = ('/archives/data/mefab/STAGING/PRODUCTION', '/archives/data/bkfb/STAGING/PRODUCTION', '/archives/data/szast/STAGING/PRODUCTION','/archives/data/cpast/STAGING/PRODUCTION');

Upvotes: 1

Views: 53

Answers (2)

lordadmira
lordadmira

Reputation: 1832

All you have to do is fix this one line.

my @listdir = $line;

to

push @listdir, $line;

Then after the loop do chomp @listdir.

The easier way is this:

@listdir = <DATA>;
chomp @listdir;

Thanks.

Upvotes: 1

Robert
Robert

Reputation: 8571

You can create the array outside the loop and push (append) new elements to it.

my @sourcedirs;
while (my $line = <DATA>) {
     chomp($line);
     push @sourcedirs, $line;
}

You could also assign the file handle to an array and chomp after reading all lines:

use strict;
use warnings;

open my $F, '<', $file or die "Cannot read $file: $!";
my @sorcedirs = <$F>;
close $F;
chomp(@sorcedirs);
print join ", ", @sorcedirs;

Or, use File::Slurp:

use File::Slurp;
my @sourcedirs = read_file($file);

Upvotes: 4

Related Questions