Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an array of directory contents?

Tags:

arrays

perl

I need to make 3 arrays from the contents of $directory. The first one I can use:

$var = qx{ls $directory};
print $var;

However, the second and third I want to grep for "Primary *" and "Secondary *"

I've used the commands:

my @primary = 0;
my @secondary = 0;

@primary = system("ls test_77 > test | grep Primary* test");
print @primary;
@secondary = system("ls test_77 > test | grep Secondary* test");
print @secondary;

But, it includes a zero on the output:

PrimaryCPE_Option_A.txt.test_77
PrimaryCPE_Option_B.txt.test_77
0SecondaryCPE_Option_A.txt.test_77
SecondaryCPE_Option_B.txt.test_77
0

What can it be? At first it looks like it might be the original zero, but I can change the initial value of either, and it doesn't work.

like image 335
Soop Avatar asked Dec 04 '25 10:12

Soop


2 Answers

Perl can do this without calling system commands.

@secondary=glob("*Secondary*.txt");
print @secondary;
@primary=glob("*Primary*.txt")
print @primary;

Other ways are using opendir()/readdir(), or while loop eg

while(my $file=<*Primary*txt>){
  push(@secondary,$file);
}

Or

push (@secondary,$_) while<*Secondary*.txt> ;
like image 55
ghostdog74 Avatar answered Dec 07 '25 01:12

ghostdog74


The following will read all the files in the current directory, and store them into one array. It excludes sub-directories, but it does include files which start with the . character. Then, it creates the 2 other arrays from the 1st array. Refer to File::Slurp.

use strict;
use warnings;
use File::Slurp qw(read_dir);

my @all_files = grep { -f $_ } read_dir('./');
my @pfiles = grep {/^Primary/  } @all_files;
my @sfiles = grep {/^Secondary/} @all_files;

I'll try to address your questions now. system returns the exit status of the external command (ls, for example). It does not return the directory listing. You would use qx to return the directory listing. Refer to system.

So, since your ls command succeeds, its exit status is 0. Thus, system returns 0. This value is stored into the 1st element of your array. That is the only value in your array. Any other output you see is coming from your grep, I believe.

Also, the only way I come close to reproducing your output is to change the pipe to a semicolon in your system call, and by getting rid of *:

@primary = system("ls test_77 > test ; grep Primary test");
like image 43
toolic Avatar answered Dec 07 '25 02:12

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!