Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

I am trying to display all elements from this array, but can't understand why the first foreach wont work.

Global symbol "$dirs" requires explicit package

How can I do this?

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @data_res = display(\@data); sub display { my @dirs = @_; foreach my $i (0 .. $#dirs) { print "$dirs->[$i] \n"; } #foreach my $i (@dirs) { #print "$i\n"; #} $VAR1 = [ '/dir/pages/books', '/dir/pages/books/2', '/dir/pages/books/2/77888k.txt', '/dir/pages/books/2/uhuhuhkk.txt', '/dir/pages/books/2/8877bg.txt', '/dir/pages/books/2/uuhu87777.txt', '/dir/pages/books/2/L', '/dir/pages/books/2/L/88uu8u.txt', '/dir/pages/books/2/L/88hhh.txt', '/dir/pages/books/2/L/uhuhuh.pdf', '/dir/pages/books/2/L/2611566_01_HA_20160819_2264063.txt', '/dir/pages/books/7', '/dir/pages/books/7/ijij8888.txt', '/dir/pages/books/7/555rf.txt', '/dir/pages/books/7/88uuhh.txt', '/dir/pages/books/7/88889kkk.txt' ];

Thank you!

Replies are listed 'Best First'.
Re: Array Ref Loop
by stevieb (Canon) on Dec 16, 2016 at 21:38 UTC

    You're passing an array reference into the display() function, but within that function, you're not extracting things properly.

    You can either do this:

    display(@data);

    ...then change your for loop in the function:

    for my $dir (@dirs){ # idiomatic perl way to loop over a list print "$dir\n"; }

    If you want to stay with the reference, you must change how you extract the parameter(s), and then dereference the array reference when using it:

    sub display { # pull out the aref passed in my $dirs = shift; # could also be `my ($dirs) = @_;` # loop over the aref. Note the syntax # could also be written with the circumfix operator: # @{ $dirs } for my $dir (@$dirs){ print "$dir\n"; } }
Re: Array Ref Loop
by Marshall (Canon) on Dec 17, 2016 at 00:12 UTC
    A few comments:

    I like stevieb's post.
    For more study, I recommend the tutorial section of Perl Monks, specifically, Data Types and Variables which talks more about references and arrays.

    Also, I think that you will find that indenting loops more than one space is much, much better (stevieb did that). A normal practice is to use either 3 or 4 spaces.