Reputation: 93
I've searched and searched online, but nothing I do seems to work. I'm aware that this is a stupidly easy question, but I'm really stuck...
I had a directory of files, and saved the names of the directories to a CSV file. It's just made up of one column of data e.g.:
100
101
102
103...
I used the following code to create the file (just in case its relevant):
open (my $fileh, '>', '/Users/Shared/serials.csv') or die "Could not open file!";
print $fileh `ls -1 $path`;
close $fileh;
print "Saved Serials!";
Now all I want is to read in the data in the file into an array, and then loop through each value to complete a task. I can't figure out how to do this...
Currently I am entering the numbers manually in the code into an array, like:
@ser_list = (100,101,102,103,...);
As stated above, I instead want to automatically write the file names (numbers) using the ls
command line query and read them back into the script from there.
If there is a way of doing this without having to make a separate file of values that would be great.
The array is called @ser_list in the example, and from there I am reading the next $ser_num from the array and working with that in the loop.
foreach $ser_num (@ser_list) {....}
Thank you all in advance for your help and patience!
Upvotes: 1
Views: 245
Reputation: 241928
Don't use ls
in a Perl program. You can use glob instead:
my @files = glob "$path/*";
If you need to work with the paths and filenames, check Path::Tiny.
To read lines with paths into an array, just use
open my $fh, '<', $filename or die $!;
chomp( my @paths = <$fh> );
See open, chomp, and readline for details.
Upvotes: 6