Current location: Hot Scripts Forums » Programming Languages » Perl » newbie perl script to call an array in a subroutine and add 1


newbie perl script to call an array in a subroutine and add 1

Reply
  #1 (permalink)  
Old 10-31-03, 09:31 AM
Arowana Arowana is offline
Newbie Coder
 
Join Date: Oct 2003
Posts: 30
Thanks: 0
Thanked 0 Times in 0 Posts
newbie perl script to call an array in a subroutine and add 1

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:
Code:
#!/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!
Reply With Quote
  #2 (permalink)  
Old 10-31-03, 01:04 PM
Chas Chas is offline
Coding Addict
 
Join Date: Oct 2003
Location: California
Posts: 359
Thanks: 0
Thanked 0 Times in 0 Posts
Quote:
Originally Posted by Arowana
Code:
#!/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:

Code:
my @new_numbers;

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

Code:
#!/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
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Forum Jump


All times are GMT -5. The time now is 04:12 AM.
vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.