On Wed, May 25, 2011 at 13:15:49 -0400 , Tim Lewis wrote:
> This is a very basic question on arrays and referring to the elements.  In
> referring to the elements, I know that it is correct practice to use $
> instead of @, but I know that Perl allows the @.  My simple question is what
> is the difference.  I have looked at different Perl tutorials, but have not
> found one that explains why to use $ over @.  Is it just common practice, or
> is there a functional reason?
> Tim
> 
> Quick example:
> my @animals = ("dog","cat");
> my $arrayCounter = @animals;
> for (my $count=0;$count<$arrayCounter;$count++) {
>   print "Critter is $animals[$count]\n"; # use $animals instead of @animals
> } 

In addition to the guidance Uri gave you, consider the following syntax:

for my $critter (@animals) {
  print "Critter is $critter\n";
}

This way you don't need to keep track of how many items you have. It's
less code to read, less code to write, and fewer places for failure all
around. Also, to be sure, the only difference between for and foreach is
expressly and specifically four characters: 'each'. They are otherwise
completely equivalent.

-- 
Chris Nehren           | Coder, Sysadmin, Masochist
Shadowcat Systems Ltd. | http://shadowcat.co.uk/

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to