Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Subroutine Even/Odd

by 2teez (Priest)
on Oct 04, 2012 at 08:16 UTC ( #997205=note: print w/ replies, xml ) Need Help??


in reply to Subroutine Even/Odd

"..I have to create the subroutine that will take the even and odd numbers from an array.."

A good compact solution has been showed by tobyink.
However, you might find the following also useful:

use warnings; use strict; my $numbers = [ 1 .. 10 ]; print even($numbers); ## call even number generator subroutine print $/; print odd($numbers); ## call odd number generator subroutine print $/; ## call combined even and odd number generator subroutine my %even_n_odd_numbers = %{ even_odd($numbers) }; for ( keys %even_n_odd_numbers ) { print $_, " ", join " ", @{ $even_n_odd_numbers{$_} }, $/; } sub even { my ($numbers) = @_; my @even_numbers; for (@$numbers) { push @even_numbers, $_ if $_ % 2 == 0; } return @even_numbers if wantarray; } sub odd { my ($numbers) = @_; my @odd_numbers; for (@$numbers) { push @odd_numbers, $_ if $_ % 2 == 1; } return @odd_numbers if wantarray; } sub even_odd { my ($numbers) = @_; my %even_odd = ( 'even' => undef, 'odd' => undef, ); for (@$numbers) { if ( $_ % 2 == 0 ) { push @{ $even_odd{'even'} }, $_; } else { push @{ $even_odd{'odd'} }, $_; } } return \%even_odd; }
The combined subroutine is a lot better, because you don't have to repeat codes lines like one did in two different subroutines ( sub even{...} and sub odd{...}) having just only one line that is different from one another.

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me


Comment on Re: Subroutine Even/Odd
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (15)
As of 2015-07-29 13:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (263 votes), past polls