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

Hi, How do I toggle the value of two variables after every itereations within my foreach loop? For ex. $var1=$value1 and $var2=$value2 and I want $value1 and $value2 to be switch between $var1 and $var2.

Replies are listed 'Best First'.
Re: Toggling vars in each iterations
by choroba (Cardinal) on Jan 17, 2013 at 02:35 UTC
    Is simultaneous assignment what you are after?
    my ($var1, $var2) = ($value1, $value2); for (@array) { ($var1, $var2) = ($var2, $var1); }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Yes, right on. I am sorry I was not able to explain question correctly but I was after simultaneous assignment as explained above. thank you.
Re: Toggling vars in each iterations
by blue_cowdawg (Monsignor) on Jan 17, 2013 at 02:23 UTC

    Post what you've tried. I barely understand what you are asking...

    foreach my $ix(1..10) { $var=($ix%2? $value1:$value2); $var=($ix%s? $value2:$value1);
    is that what you are after perhaps?


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
      Sorry my bad: Here is what I am looking for: In below example I have $var1 value as 10 and $var2 as 5. For each iteration I want values to switch between these two. i.e. Iteration 1: $var1=10 and $var2=5 Iteration 2: $var1=5 and $var2=10 Iteration 3: $var1=10 and $var2=5 Iteration 4: $var1=5 and $var2=10 so on and so forth. I tried something like below which is incorrect use strict; use warnings; my $var1=10; my $var2=5; foreach(1..10) { $var1=$var2; $var2=$var1; print "Var1 is:$var1\n"; print "Var2 is:$var2\n"; }

        Hello akki_best, and welcome to the Monastery!

        $var1 = $var2; $var2 = $var1;

        That won’t work, because by the time you get to the second command, the value of $var1 has already been overwritten by the first command. But in Perl, swapping these values is as simple as:

        ($var1, $var2) = ($var2, $var1);

        P.S. Please format your code using <code> tags. See Markup in the Monastery.

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,