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

Multiple assignment in Perl

by rnaeye (Friar)
on Jul 22, 2018 at 23:27 UTC ( [id://1219064]=perlquestion: print w/replies, xml ) Need Help??

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

In Python I can do the following:

a, b = 0, 1 while b < 50: print(a, b) a, b = b, a + b

That is shorter version of the following assignment (I think they call it atomic version):

old_a = a a = b b = old_a + b

How do I do the first assignment in Perl? My Perl version is

use warnings; use 5.18.2; my ($a, $b) = (0, 1); while ($b < 50) { say "$a $b"; my $old_a = $a; $a = $b; $b = $old_a + $b; }

Thank you.

Replies are listed 'Best First'.
Re: Multiple assignment in Perl
by Anonymous Monk on Jul 22, 2018 at 23:36 UTC
      That is embarrassing for me! It was the first thing I tried; it did not work for me at the time. I must have made a typo, etc. Thank you.

        Maybe on your first attempt, you put an extra my in front of it? That would cause issues because it would declare two new variables within the while loop which would mask the old variables.

        Also, $a and $b are really bad variable names to choose in Perl. There are special variables with these names used by sort so using them for other stuff can occasionally cause issues. $x and $y would be fine, as would more meaningful variable names.

Re: Multiple assignment in Perl
by bart (Canon) on Jul 24, 2018 at 06:13 UTC
    In Perl, the "," operator has a lower precedence than "=". Therefore, your version means
    $a, $b = $b, $a + $b
    which does, practically speaking, nothing.

    You have to add parens to enforce the proper precedence.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1219064]
Approved by biohisham
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-03-28 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found