Home > Back-end >  Cast array into list
Cast array into list

Time:01-28

I have a file that I need to read into a list so I can use it in Template Toolkit. I can do that easy with array and I am bit struggling with list. Is there a way to cast array into list?

# file.txt
foo
bar
zoo
my $filename = shift;
open(my $fh, '<:encoding(UTF-8)', $filename)
  or die "Could not open file '$filename' $!";
while (my $row = <$fh>) {
  chomp $row;
  unshift @yy_array, $row;
}

my $zz_list = ['foo', 'bar', 'zoo'];

say "### Dumper - array ###";
print Dumper \@yy_array;
say "### Dumper - list ###";
print Dumper $zz_list;

### Dumper - array ###
$VAR1 = [
          'zoo',
          'bar',
          'foo'
        ];
### Dumper - list ###
$VAR1 = [
          'foo',
          'bar',
          'zoo'
        ];
###

Any thoughts?

CodePudding user response:

What you call a list is an array reference. You can use the reference operator to get a reference to an array:

my $array_ref = \@array;

Another option is to create a new anonymous array and populate it by the elements of the array:

my $array_ref = [@array];

To get the array back from the reference, you dereference:

my @arr2 = @{ $array_ref };
  •  Tags:  
  • perl
  • Related