Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Duplicate variable returned from sub

by Zenzizenzizenzic (Scribe)
on Sep 23, 2019 at 16:44 UTC ( #11106576=perlquestion: print w/replies, xml ) Need Help??

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

Looking at old cold, I'm seeing some lines like
my ($var1, $var2, $var3, $var1) = someFunction($var4);
Since the $var1 is declared twice, use warnings; flags it. I assume the latter instance will be the one kept, but is this correct? Thank you

Replies are listed 'Best First'.
Re: Duplicate variable returned from sub
by Your Mother (Bishop) on Sep 23, 2019 at 16:59 UTC

    It’s easy enough to test–

    perl -Mstrict -wE 'my ( $v1, $v2, $v1 ) = ( 1 .. 3 ); say $v1' "my" variable $v1 masks earlier declaration in same statement at -e li +ne 1. 3

    I would not rely on the behavior though. Definitely fix it by cutting out the duplicates.

      I am addressing the code issue, yes. Since we're running this on Linux and Solaris, I really don't want to rely on a "quirk" that the code run the same. Thank you!

        You could make this explicit by using:

        my (undef, $var2, $var3, $var1) = someFunction($var4);
        or refactoring someFunction() if that makes sense.

Re: Duplicate variable returned from sub
by BillKSmith (Prior) on Sep 23, 2019 at 19:21 UTC
    your error message tells you "my" variable $var1 masks earlier declaration in same statement... This has nothing to do with the function. Fix the declaration, and the assignment will work as you expect.
    use strict; use warnings; sub someFunction { return @{$_[0]} } my ($var1, $var2, $var3); my $var4 = [qw(1 2 3 4)]; ($var1, $var2, $var3, $var1) = someFunction($var4); print "$var1 $var2 $var3\n"; OUTPUT: 4 2 3
    Bill
      This was more for knowing the way Perl handled the situation, in case I need an immediate fix. I am changing the function itself. No errors/warnings given as the code was NUWNUS.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11106576]
Approved by Athanasius
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2020-10-23 03:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (234 votes). Check out past polls.

    Notices?