in reply to Perl list items

1 is the number of elements in the list.

This line:

@A = join( "," .....

Creates a single element that is a string containing a bunch of comma delimited data.

This line:

$A = @A;

Evaluates @A in scalar context, which causes Perl to assign a count of the number of elements in @A to $A.

Those issues will be discussed in perlintro, and join.

In particular, the purpose of join is to turn a list into a single scalar value.


Dave

Replies are listed 'Best First'.
Re^2: Perl list items
by frozenwithjoy (Priest) on Jul 09, 2012 at 15:36 UTC

    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;
      "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.

        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'