Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Pure variable confusion!

by aaron_baugher (Curate)
on Apr 22, 2015 at 00:42 UTC ( [id://1124210]=note: print w/replies, xml ) Need Help??


in reply to Pure variable confusion!

my @average = $num_list_total / $size; print "The average of the numbers is @average.\n";

This is a bug waiting to happen. $average is a scalar variable containing a single value. @average is an array variable containing a list of values. You're getting away with it here because the first line puts the result of the division in the first element of @average, and then the print statement prints out the whole array, which happens to have only that one element. But if you assigned or used the value a bit differently, it could easily break. Use scalar variables for single values.

@average = average(@_);

Same problem here, assigning what's likely a single value to an array (which will be a problem in a few lines). You're also calling a subroutine named average() which doesn't exist in your script, which means your script doesn't run at all. Have you actually tried running it as it exists here?

Anyway, that line assigns the result of the average() call to the first element of @average. Which means that this line doesn't do what you want:

    if ($element > @average) {

Since this evaluates @average in scalar context, it uses the number of elements in @average, not the value(s) stored in it. Since you (presumably) stored a single value in it, this has the effect of:

    if($element > 1){

So again, store your single values in scalar variables. That's a bigger problem than whatever confusion you may be causing by localizing the same variables inside and outside your subroutine.

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found