2

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?

6
  • 1
    I don't understand. The file gets read, line by line, and you store those lines in the array @yy_array (in reverse order). What do you need to do with that? (Btw, what you call a "list", [...], is an array reference.) Commented Jan 27, 2023 at 21:59
  • I need to refer it in the template toolkit and it accept only a list: template-toolkit.org/docs/manual/… Commented Jan 27, 2023 at 22:06
  • OK. I last looked at that years ago, let me see... Commented Jan 27, 2023 at 22:08
  • Thanks! I looked a number of question but I am unsure if there is a "simple" way stackoverflow.com/questions/34685788/convert-array-to-list Commented Jan 27, 2023 at 22:09
  • 1
    Template Toolkit's documentation uses incorrect terminology. It wants a reference to an array (aka array reference). There's no such thing as a reference to a list (or list reference) since list isn't a type of variable in Perl. Commented Jan 27, 2023 at 23:50

1 Answer 1

7

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

2 Comments

Thats it! I tried join/split/cat but I got a number instead. I understand what is an array reference (well, I guess not), the ARRAY(0x1246). Do you mind elaborate how this work internally?
See perlref and perlreftut. Also, updated with a dereference example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.