Bagarre has asked for the wisdom of the Perl Monks concerning the following question:

Hello. Why is it that
my ($var1, $var2, $var3) = "Hello";
..not the same as
my $var1 = "Hello"; my $var2 = "Hello"; my $var2 = "Hello";
??? Thanks.
Entities should not be multiplied unnecessarily.

2006-11-03 Retitled by planetscape, as per Monastery guidelines

( keep:1 edit:12 reap:0 )

Original title: 'Whis is this not?'

Replies are listed 'Best First'.
Re: Please explain 'list' assignment.
by Errto (Vicar) on Nov 03, 2006 at 19:11 UTC
    The way to do what you're looking for is
    my $var1 = my $var2 = my $var3 = "Hello";
    The reason your first piece of code doesn't do that is because it's a list assignment. That is, it takes a list of variables on the left side and a list of values on the right side. But the list on the left side has three items and the list on the right only has one, so the other two variables will get a value of undef.
Re: Please explain 'list' assignment.
by friedo (Prior) on Nov 03, 2006 at 19:10 UTC

    Because list assignments are parallel. A list of three items on the left expects three items on the right. Since there's only one, $var2 and $var3 remain undefined.

    You can do what you want with:

    my ($var1, $var2, $var3) = "Hello" x 3;

    Update: Oops - I read your question slightly wrong. To assign the same value three times, use

    my ($var1, $var2, $var3) = map "Hello", 1..3;
    my ($var1, $var2, $var3) = ("Hello") x 3;
    (thanks Sidhekin)

      The 'x' operator can act upon strings or upon lists. The use above, "Hello" x 3" created three concatenated copies of the string "Hello", thus "HelloHelloHello". What you wanted was "three copies of an item in list context", like so:
      my ( $var1, $var2, $var3 ) = ("Hello") x 3;
      The parentheses force the value into list context, the 'x' then makes three copies of that single value list, and you get ("Hello", "Hello", "Hello"), which is what OP wanted.
      Just came back to say that didnt work :) The map works... and makes sense.
      Entities should not be multiplied unnecessarily.
      Perfect. Thank you :)
      Entities should not be multiplied unnecessarily.
Re: Please explain 'list' assignment.
by NetWallah (Canon) on Nov 04, 2006 at 07:06 UTC
    TIMTOWTDI - I prefer the option below, because it allows you to expand the list, without counting the number of variables, is easy to read, and is economical in the number of keystrokes required :
    $_='Hello' for my ($x,$y,$z);

         "A closed mouth gathers no feet." --Unknown