Thanks Uri.  That makes perfect sense.

-----Original Message-----
From: Uri Guttman [mailto:u...@stemsystems.com] 
Sent: Wednesday, May 25, 2011 1:37 PM
To: Tim Lewis
Cc: beginners@perl.org
Subject: Re: Basic question on arrays $ vs @

>>>>> "TL" == Tim Lewis <twle...@sc.rr.com> writes:

  TL> This is a very basic question on arrays and referring to the
  TL> elements.  In referring to the elements, I know that it is correct
  TL> practice to use $ instead of @, but I know that Perl allows the @.
  TL> My simple question is what is the difference.  I have looked at
  TL> different Perl tutorials, but have not found one that explains why
  TL> to use $ over @.  Is it just common practice, or is there a
  TL> functional reason?  Tim

  TL> Quick example:
  TL> my @animals = ("dog","cat");
  TL> my $arrayCounter = @animals;
  TL> for (my $count=0;$count<$arrayCounter;$count++) {
  TL>   print "Critter is $animals[$count]\n"; # use $animals instead of
@animals
  TL> } 

the sigil is supposed to tell you how many elements you are getting from
the array. $animals[0] is obviously one elements. @animals[0,1] is
getting two elements and is called a slice. so @animals[0] is also a
slice and is legal but misleading, it should use a $ for the
sigil. where slices really come into play and can legimaitely get one
element is when the the indexes are in an array. then you need the @
sigil as the index is also in list context (the prefix sigil does
provide the context for inside the []).

        @indexes = ( 0 ) ;
        print @animals[@indexes] ; # prints 'dog'

note that if you use a $ like this:

        print $animals[@indexes] ; # prints 'cat'

it prints cat since @indexes in scalar context is 1 which is the index
used to get cat.

so there is a warning in perl if you use a scalar (single literal value
or scalar var) when indexing an array slice. it means you chose a list
context for indexing but explicitly indexed with one value. yes, it
works and is legal but it is not good coding.

uri

-- 
Uri Guttman  ------  u...@stemsystems.com  --------  http://www.sysarch.com
--
-----  Perl Code Review , Architecture, Development, Training, Support
------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com
---------

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



-- 
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