PDA

View Full Version : newbie perl script to call an array in a subroutine and add 1


Arowana
10-31-03, 10:31 AM
Hi all,

I am trying to write a subroutine which is passed an array. It returns nothing. The routine should add 1 to every value of the array. What would this look like? Here's what I have:

#!/usr/bin/perl
use strict

@numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
sub plus_plus {
print ("++$1 '@numbers'");
}



Like, the answer would be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Right now, if I run the script, it just returns to the command line.

I'm a total perl newbie (ya can tell ) Can someone help me out with this? I have a real hard time with arrays and subroutines... Thanks!

Chas
10-31-03, 02:04 PM
#!/usr/bin/perl
use strict

@numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
sub plus_plus {
print ("++$1 '@numbers'");
}



You never actually call your sub, that's why nothing is happening. Even if you did call it, there are a few problems.

You would need to iterate over the values in the array to do something useful:


my @new_numbers;

foreach my $number (@numbers) {
# Do something useful with $number here. i.e.:
push(@new_numbers, ++$number);
}


But map (http://www.perldoc.com/perl5.8.0/pod/func/map.html) is your friend here:


#!/usr/bin/perl -w
use strict;

my @numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

# Call your sub here:
my @new_numbers = plus_plus(@number);

sub plus_plus {
return map { $_ + 1 } @_;
}


~Charlie