简体   繁体   中英

Cast array into list

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?

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM