Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: returnong array in custom subroutine

by stevieb (Canon)
on Aug 31, 2016 at 13:51 UTC ( [id://1170890]=note: print w/replies, xml ) Need Help??


in reply to returning array in custom subroutine

You've got a few issues with your code. You're re-declaring some of your variables with my incorrectly (always put use warnings; and use strict; at the top of your scripts), you're using @array in a global sense when you should be passing it into the subroutine instead, and unless you have good reason not to, you should be putting your use statements at the top of your code as it's far easier to see what the code is using.

With these changes and additions, does it do what you expect? I create the array, send it in as a list of parameters to the sub, perform actions on each element, push the result to a new array, then when done the loop, return the entire new array:

use warnings; use strict; use List::Util qw( min max ); my @not_normalized = qw(5 4 9 9 6); my @normalized = normalizer(@not_normalized); print "$_\n" for @normalized; sub normalizer { my @not_normalized = @_; my $min_numarray = min @array; my $max_numarray = max @array; my $normalized; my @normalized_list; foreach my $element (@not_normalized){ my $numdiv = $element - $min_numarray; my $numden = $max_numarray - $min_numarray; $normalized = $numdiv / $numden; push @normalized_list, $normalized; } return @normalized_list; }

Output:

0.2 0 1 1 0.4

update: renamed arrays to have sensible names

Replies are listed 'Best First'.
Re^2: returnong array in custom subroutine
by dovah (Novice) on Aug 31, 2016 at 13:58 UTC
    Yes, thanks! :) this is what I expected.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-19 23:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found