Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

looping through array

by manishrathi (Beadle)
on Jan 07, 2010 at 21:41 UTC ( #816177=perlquestion: print w/ replies, xml ) Need Help??
manishrathi has asked for the wisdom of the Perl Monks concerning the following question:

1)
@trial_array = ("first", "second", "third");


to access second elements of the array, I can use following syntax

$sec_el = $trial_array[1];


now if I am reading in a file datacapture.cgi which has following content
"this is a data file. This ie read in array. this is looped through"
$datafile = datacapture.cgi; open(DAT, $datafile); @data_array = <DAT>;
now each line becomes an element of @data_array. so there are three elements $data_array[0], $data_array[1] and $data_array[2] in @data_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 ?
foreach $loopvariable (@data_array) { print $loopvariabe ; }
does it mean that $loopvariable will be assigned the elelments of @data_array one by one ? or do I need to use $data_array[] directly ?

foreach (@data_array)
{ print $data_array ; } #this looks like wrong syntax

2) 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 ?

Comment on looping through array
Select or Download Code
Re: looping through array
by kennethk (Monsignor) on Jan 07, 2010 at 21:48 UTC
    1) For some information about this from the documentation, see For Loops and Foreach Loops in perlsyn. The short of it is you can define your own loop variable if you like, or not define it and have your elements assigned to the magic variable $_. Like this:

    foreach my $loop_variable (@data_array) { print $loop_variable; }

    or this:

    foreach (@data_array) { print $_; }

    As a side note, see how all your array elements are links? That is because you did not wrap your code in <code> tags. See Writeup Formatting Tips.

    2) You are not declaring array elements so much as defining strings and storing those in your array. Your syntax will work so long as you have a comma separated list of strings. That means you can use pairs of single quotes, pairs of double quotes or any of a host of delimiters listed in Quote and Quote like Operators. For your case, you may be particularly interested in the qw() delimiter, since that uses whitespace to delimit your strings instead of commas.

Re: looping through array
by biohisham (Priest) on Jan 07, 2010 at 22:27 UTC
    It'd be very neat if you separated your code and placed it within the special "<code>" and "</code>" tags.

    "Do we need to declare array elemnts in double quotes"

    @array1 = ('one','two','three'); @array2 = ("four","five","six"); print "@array1\n@array2"; #OUTPUT one two three four five six
    You can use Perl's quote like operators instead if you did not want to use quotes, however, using single quotes and double quotes can be critical when you want to interpolate ...consider the following quick example and see the differences in the output...
    @array = qw(one two three); print @array, "\n"; print "@array\n"; print '@array\n'; __END__ onetwothree #array elements are fused. one two three #spaced and the "\n" replaced with a new line. @array\n #prints @array and "\n" as literals.
    Let's expand on... Guess what the outcome of the code below is, as an exercise :
    use strict; #a good habit to start your program with line use warnings; #another good habit too... my @array1 = ("one", "two", "five"); my @array2 = ("three","four"); my @array3 = ("one","two",@array2,"five"); my @array4 = ("one","two",'@array2',"five"); my @array5 = ("one","two","@array2","five"); print "@array3\n"; print "@array4\n"; print "@array5\n";

    You can loop through your array with a for loop iteration too and using an incremented index allows you to access array elements in turns.

    @array = qw(one two three four); for($index=0;$index<=$#array;$index++){ print $array[$index],"\n"; }
    Read more at for loops and foreach loops, other than that, you can try and see for yourself if something really works and observe the behavior differences by experimenting on your options, this can let you discover new things as well as solidify your knowledge of something you learnt..

    Update: Added examples...


    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.
      @array = qw(one two three); print @array, "\n"; print "@array\n"; print '@array\n'; __END__ onetwothree #array elements are fused. one two three #spaced and the "\n" replaced with a new line. @array\n #prints @array and "\n" as literals.


      I understand first output as all the array elements are printed in a row.

      I dont understand second output. When print command is used with array name in quotes, output has a space between elements. where does this space come from ?

      In the third output, everything in single quotes is printed as literal. Does it mean that anything in single quotes is treated as literal and will be printed as is. Anything in double quotes will be treated as string value with variables getting its values from the code ?
        is anything within single quotes is always treated as literal in print statement ?
        anything in double quotes is treated as string with variables getting their values from the code ?
        whats the difference between when an array elements are declared in single quotes, double quotes and without quotes ? I tried out all the ways and I get the same result.
        I dont understand second output. When print command is used with array name in quotes, output has a space between elements. where does this space come from ?

        The Perl print built-in prints a list with the $, special variable interpolated between each item.

        Double-quoted strings (which have nothing directly to do with print) interpolate arrays with the $" special variable interpolated between each array element. See the documentation in perlvar for the default values of the  $, and  $" special variables.

        In the third output, everything in single quotes is printed as literal. Does it mean that anything in single quotes is treated as literal and will be printed as is.

        Yes. Whether printed or not, there is no interpolation in single-quoted strings. The  \ (backslash) character has limited effect as an escape under conditions explained in the docs on single-quoted strings linked by other respondents.

        Anything in double quotes will be treated as string value with variables getting its values from the code ?

        Yes and no. Double-quoted strings interpolate scalar and array variables as per the docs.

        >perl -wMstrict -le "my @array = ('one', qw(two three), qq{four}); print @array; $, = 'FOO'; print @array; print qq{@array}; $\" = 'BAR'; print qq{@array}; " onetwothreefour oneFOOtwoFOOthreeFOOfour one two three four oneBARtwoBARthreeBARfour
Re: looping through array
by AnomalousMonk (Abbot) on Jan 07, 2010 at 23:07 UTC
    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 ?
    foreach $loopvariable (@data_array) { print $loopvariabe ; }
    does it mean that  $loopvariable will be assigned the elelments of @data_array one by one ?
    foreach (@data_array) { print $data_array ; } #this looks like wrong syntax
    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 ?

    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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://816177]
Approved by kennethk
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (10)
As of 2014-12-26 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (167 votes), past polls