in reply to Re: Exchanging Variables
in thread Exchanging Variables

No way! You are saying that all I have to do is:
($first,$second) = ($second,$first);

and it automatically exchanges them for you?

Is there any other ways of doing this that might be used for other tasks? Or is this the only *reasonable* way to do it?

Mr.T
qw/"I pity da foo' who don't use Perl!"/;

Replies are listed 'Best First'.
Re: Re: Re: Exchanging Variables
by Ven'Tatsu (Deacon) on Aug 10, 2001 at 01:22 UTC
    Asigning an array to a list of variables is a common way to give meaning full names to the items in an array. You can use it to make handling the returns of functions like local time easyer.
    IE:
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); as opposed to
    @time = localtime(time); and having to remeber that $time[2] is the hour.

    If you have an array in the list on the left side of the = it will gobble up all the remaing items in the array on the right side. You need to be careful of this, because anything following the array will not have anything asigned to it.
    IE:
    ($one, $two, @three, $four) = ('one', 'two', 'three', 'four'); $one will equal 'one'
    $two will equal 'two'
    @three will equal ('three', 'four')
    and $four will be undefined

    There are many ways to use this feature of perl.
    You will probably see
    sub do_stuff { my ($foo, $bar) = @_; }
    to get the arguments sent to a subroutine into named variables often.
Re: Re: Re: Exchanging Variables
by premchai21 (Curate) on Aug 10, 2001 at 01:09 UTC
    Basically, whenever you assign to a list, each element gets assigned to, all in parallel. So, in parallel, the value of the first gets assigned to the second, and the value of the second (which isn't *yet* the previous value of the first) gets assigned to the first; thus, they get exchanged. See?
Re: Re: Re: Exchanging Variables
by dga (Hermit) on Aug 10, 2001 at 01:55 UTC

    This is otherwise known as DWIM, Do What I Mean.

    Cool aint it?

Re: Re: Re: Exchanging Variables
by John M. Dlugosz (Monsignor) on Aug 10, 2001 at 02:03 UTC
    re: Is there any other ways of doing this that might be used for other tasks? Or is this the only *reasonable* way to do it?

    You might want to ask that in the Obfuscation section and then stand back.

    how about:

    push @INC, $first, $second; # not a temporary since it already exists! $_= pop @INC foreach ($first, $second);

      or, uhm...

      $x = substr($x.$y, -(length($y) * ($y =~ s/^$y$/$x/)), length($y));

      update: substr, not suystr. sorry. Thanks John.

Re: Re: Re: Exchanging Variables
by suaveant (Parson) on Aug 10, 2001 at 00:24 UTC
    You can do that... I believe it has something to do with perl creating a temporary anonymous array... but I am not entirely sure...

                    - Ant
                    - Some of my best work - Fish Dinner