in reply to Re: Problem with parameters in subroutines
in thread Problem with parameters in subroutines

Ok thanks for explanation. Im already learning perl from yesterday and sometimes it looks strange for me :) I have got next question with loops: If i have got loop:
foreach $guest(@people) { if($guest->{'ident'} =~ /^1[014689]*7[014689]*5[014689]*3[ +014689]*2[014689]*$/) { mywrite($guest); #my print function } }
And i want change this foreach loop to for loop it should looks like that?
$arraylenght = lenght($guests); for($i = 0 ; i < $arraylenght ; $i++) { }
Im thinking how i can change this loop foreach to for loop workinkg for this example im trying to do this to practise. I was reading abour foreach loop and i think here guests is a array of people and &guest are one person from this array. Is it maybe possible to do something like this?
$arraylenght = lenght($guests); for($i = 0 ; i < $arraylenght ; $i++) { if($guest->{'ident'} =~ /^1[014689]*7[014689]*5[014689]*3[014689]*2[01 +4689]*$/) { mywrite($guest); #my print function } }

Replies are listed 'Best First'.
Re^3: Problem with parameters in subroutines
by smls (Friar) on Jun 02, 2014 at 14:30 UTC

    This is how you would write it as a C-style for loop:

    for (my $i=0; $i <= $#people; $i++) { if($people[$i]{'ident'} =~ /^1[014689]*7[014689]*5[014689]*3[01468 +9]*2[014689]*$/) { mywrite($people[$i]); #my print function } }

    Comments:

    • @people is an array, and $people[$i] is the element with index $i in that array. The foreach version of the loop automatically maps the current array element to a new variable ($guest in this case) which is nicer to type and read than $people[$i], which is why that kind of loop is usually preferable.

    • $#people is the correct syntax for referring to the last index of the @people array. The length function is only used to get the length of a string, not the number of elements in an array.

    In any case, I strongly recommend that you carefully read through the whole perlintro page (and especially the "Perl variable types" section); it will make learning Perl much easier than trying to figure out the basics by trial-and-error. After that, perlreftut makes for good further reading.

    ---
    Update: Fixed link; thanks taint!

      Did you perhaps mean:

      functions: length EXPR, in your link above, smls? :)

      --Chris

      UPDATE:
      NP smls. I don't even want to count the times I've done it. :)

      ¡λɐp ʇɑəɹ⅁ ɐ əʌɐɥ puɐ ʻꜱdləɥ ꜱᴉɥʇ ədoH