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

Hi,

I have a constant array like the below


use constant VALUES => qw(1,2,3,4,5);

I want to loop through this constant array. Any idea how can I do this?<>br
Thanks,
George

Replies are listed 'Best First'.
Re: Loop through a constant array
by kennethk (Abbot) on Nov 10, 2009 at 02:10 UTC
    You can cycle through the list just like you would with any array. The easiest approach is likely a foreach loop:

    use strict; use warnings; use constant VALUES => qw(1 2 3 4 5); foreach (VALUES) { print; }

    As a side note, in your OP you have used a comma-delimited list with qw delimiters - see the information on Quote and Quote like Operators in perlop. If you are not getting the results you expect, I'd bet that's your issue and use warnings; will tell you as much.

    Lastly, since you are trying to use <br> tags, you should read Markup in the Monastery.

Re: Loop through a constant array
by stevieb (Canon) on Nov 10, 2009 at 03:41 UTC

    ++ for kenneth, but I prefer to name the iteration item. This way, if your routine grows larger, it's easy to identify what is what, instead of relying on $_:

    #!/usr/bin/perl use warnings; use strict; use constant VALUES => qw( 1 2 3 4 5 ); for my $value ( VALUES ) { print "$value\n"; }

    Steve