Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^2: Warnings on unused variables?

by Animator (Hermit)
on Sep 28, 2008 at 12:46 UTC ( [id://714161]=note: print w/replies, xml ) Need Help??


in reply to Re: Warnings on unused variables?
in thread Warnings on unused variables?

Another case that is missing is when functions are called via a dispatch table and are passed a list of variables. (Which the function may or may not need.)

In the current code base at work each functions recieves 5 common arguments. Some will use all of them, others only one.

Replies are listed 'Best First'.
Re^3: Warnings on unused variables?
by AZed (Monk) on Sep 28, 2008 at 16:02 UTC

    I'm a little confused here... why would that trigger an unused warning? The variables in the calling code will be used, and the receiving function will be declaring its own, assigning out of @_, and discarding the rest, so it shouldn't have a problem either.

    Could you post an example?

      For example:

      sub foo1 { my ($c, $d, $e, $f) = @_; return $d * f; } sub foo2 { my ($c, $d, $e, $f) = @_; return $c + $d + $e + $f; } sub do_foo { my $which = $_[0] ? \&foo1, \&foo2; $which->(1, 2, 3, 4); }

      As you see foo1 uses only uses the second argument and fourth ($d, $f). But the assignment happens via my ($c, $d, $e, $f) = @_;. If a warnings is introduced for lexical variables that are used once then it will warn. (lexicals $c and $e are declared and initialized but never used.

      Yes, the assignment could be changed into: my ($d, $f) = @_[1, 3]; but this would be worse from a maintenance point of view.

      With my ($c, $d, $e, $f) = @_; you know exactly what parameters are passed (assuming they get a decent name). If you use my ($d, $f) = @_[1, 3]; then you are clueless about the other arguments.
      If you later need the other arguments then you need to start looking in what order they were passed.

        What I'm not seeing is why you would think that $c or $e could have a name better than undef.

        sub foo1 { my (undef, $d, undef, $f) = @_; return $d * $f; }
        ... works just fine, produces no warnings, and has the added advantage of immediately giving the parameter a name that makes it absolutely clear that the value will be discarded.
Re^3: Warnings on unused variables?
by ikegami (Patriarch) on Sep 28, 2008 at 21:12 UTC
    It wasn't meant to be an exhaustive list. They were the examples other people wrote in the P5P list thread.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://714161]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-16 18:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found