James Hawkins James Hawkins - 3 months ago 6x
Perl Question

Loading Files into dimensioned array in perl

I am trying to create a perl script to load file contents into a dimensioned array and it does not seem to be working. Any help would be greatly appreciated!

This is what I am trying but it is not working.

use List::Util qw(first);
@filelist = ("file1", "file2", "file3");

sub Load_File{
my $File_Name = shift;
open my $handle, '<', $File_Name;
chomp( my @lines = <$handle>);
close $handle;
return @lines;

$filelist[0] = Load_File(@filelist[0]);

print "$filelist[0][1]\n";

My expected results would be for $filelist[0] to == "file1" and $filelist[0][0] to return the first line of the file with each subsequent sub-array entry being a line in the file.

Data format visualization

$filelist[0] == "file1"
$filelist[0][0] == "Line1 of file1"
$filelist[0][1] == "Line2 of file1"
$filelist[0][2] == "Line3 of file1"
$filelist[1] == "file2"
$filelist[1][0] == "Line1 of file2"
$filelist[1][1] == "Line2 of file2"
$filelist[1][2] == "Line3 of file2"

So what am I doing wrong?

Thank you


Thank you for the responses and clarification!

It looks like I am going about this wrong. I am trying to make an automatic random playlist generator. The intent was to set up text files which are just lists of song locations, each text file being a given genre. Then to have the script randomly select one or more songs from each genre and output a randomized M3U playlist. Allowing me to set some genre's to occur at given points. Like select 4 country songs, then 1 hard rock, then 3 of another.

My thought was to use the dimensioned array's then when an array was empty to remove it from the filelist. Using splice with rand to grab a song, remove it from the array, thus random selection would not slow down as it would be selecting from an ever smaller array.

From reading the responses I may have gone down a dead end and need to rethink how to solve it. Pointers are appreciated!


You can't get such structure in Perl (and many other languages for that matter). Each of your second level is actually a separate array and your first level array cells hold reference to those sub-arrays as value. So $filelist[0] = [ "Line1 of file1", "Line2 of file1", "Line3 of file1" ]. $filelist[0] can't be both "file1" and [...] at once.

(Well, it is Perl we're talking about, so actually you can, because with enough knowledge of internals you can do many insane things. But you really shouldn't go there at your level and even if you find out how to do that later, you shouldn't do that because it would be unreadable and unmantainable.)