in reply to Assignments for Subroutines
As the other answer said, none of these functions receive any arguments, nor do they return anything meaningful.
In Perl, to pass arguments to a function, you put them in parentheses after the function name, a la:
my @nums = 1 .. 10; my @results = evens(@nums);
And within the functions, to receive arguments, you pull them out of the @_ array.
sub evens { my (@nums) = @_; ...; }
To return something, you either use the return keyword, or make sure that the thing you want to return is the last statement executed in the sub.
sub this_sub_returns_1 { return 1; 2; } sub this_sub_returns_2 { 1; 2; }
Here are even and square rewritten to actually take arguments and return values. There's also even_better and square_better which do the same thing but more concisely. (Whether they are "better" is a judgement call. I prefer them though.)
use strict; use warnings; # Write a subroutine (&evens) that recieves an array of numbers and re +turns # an array containing only even numbers Give an example of calling the + # subroutine. sub even { my (@nums) = @_; my @evens; foreach my $number (@nums) { if ($number % 2 == 0) { push @evens, $number; } } return @evens; } print "Results for even(1..10)\n"; print "$_\n" for even( 1 .. 10 ); sub even_better { grep { $_ % 2 == 0 } @_; } print "Results for even_better(1..10)\n"; print "$_\n" for even_better( 1 .. 10 ); # Write a subroutine(&squares) that recieves an array of numbers and # squares each number in the array. Note: nothing is returned. sub square { foreach my $number (@_) { $number *= $number; } return; } print "Results for square(1..10)\n"; my @nums = 1 .. 10; square(@nums); print "$_\n" for @nums; sub square_better { $_ *= $_ for @_; } print "Results for square_better(1..10)\n"; my @nums_better = 1 .. 10; square_better(@nums_better); print "$_\n" for @nums_better;
|
|---|