in reply to looping through array
if I want to loop through this array using foreach, do I need to use $data_array variabke only or can I use any variable ?does it mean that $loopvariable will be assigned the elelments of @data_array one by one ?foreach $loopvariable (@data_array) { print $loopvariabe ; }Do we need to declare array elemnts in double quotes only or can we declare it in single quotes also ? what if array elements are declared without any quotes ? will it be a syntax error ?foreach (@data_array) { print $data_array ; } #this looks like wrong syntax
Not to discourage asking questions, but even without Resort to The Fine Manuals linked by other respondents, these questions can also be answered by experimentation. Note: Using warnings and strictures (use warnings; use strict; or -wMstrict on the command line) while experimenting can be very informative.
>perl -wMstrict -le "my @array = qw(one two three); for my $loopvariable (@array) { print $loopvariable; } " one two three >perl -wMstrict -le "my @array = qw(one two three); for (@array) { print $array; } " Global symbol "$array" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.
Note also that the loop variable is aliased to the elements of the list over which the loop iterates; it can be used to change them (if they are changeable!).
>perl -wMstrict -le "my @array = ('two', 'three', 'four'); for my $loopvariable (@array) { ++$loopvariable; } print qq{@array}; " twp thref fous
|
|---|