Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^2: Perl list items

by frozenwithjoy (Priest)
on Jul 09, 2012 at 15:36 UTC ( [id://980706]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl list items
in thread Perl list items

To elaborate on davido's good answer, if you had used ( $A ) = @A instead, @A would have been evaluated in list context and $A would have the value of the first element of $A, which could have also been written as $A[0] (i.e., the 1st element of @A).

Part of my point in writing all these different versions of A is to demonstrate that choosing the same name for a scalar and an array is confusing. It is much more readable to have distinct, concise, yet descriptive names.

One more thing... When troubleshooting your code, it can be helpful to print the contents of your variables to make sure things look as expected. This is simplest for scalars. For more complex structures, Data::Dumper and Data::Printer are very handy. I prefer Data::Printer since you need to type less, there is auto-indexing and pretty color coding. Here is a usage example (it is more impressive on complex hashes, etc.):

use Data::Printer; p @A;

Replies are listed 'Best First'.
Re^3: Perl list items
by monsoon (Pilgrim) on Jul 09, 2012 at 16:07 UTC
    "Part of my point in writing all these different versions of A is to demonstrate that choosing the same name for a scalar and an array is confusing. It is much more readable to have distinct, concise, yet descriptive names."
    Is it also not a good idea to use the same name for scalar and array in a loop? I tend to do this all the time
    foreach my $item (@items){ ... }
    UPDATE:lol, what a blunder. I guess I use this construct so much that these names look the same to me (aside from having a different sigil), whereas they really are different.
      Well, in your example, they have different names (one is plural, one is singular). I think at this point it comes down to personal preference. It might be easy to get the similar names confused, but you won't easily call one when you mean the other by simply making a $/@ typo.
        Thank you for your help, but how would you guys take the first five items(numbers and letters) from this Scalar string that is @A? Can i use split for that?

      Nitpicking perhaps, but "item" and "items" are different names. :-)

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://980706]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-24 06:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found