Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie sending parameters to functions in perl

Status
Not open for further replies.

r2d22y

Technical User
Nov 30, 2004
46
SE
Hello

I'm a newbie of PERL and have a question about sending parameters to functions. As I understand the parameters are stored in an array so lets say I do as below

my $i="test"
my @tmp=("1","2","3");
writeThis(@tmp,$i);
.
.
.
sub writeThis(){
my @tmplocal=shift;
my $ilocal=shift;
print "My array: ".$tmplocal."\n";
print "My i: ".$ilocal."\n"
}

Would print out :
My array: 1 2 3 test
My i:

How should I do so my "sub function" understands that there are 2 parameters sent?

/D_S
 
Try this:
Code:
#!/usr/bin/perl -w
use strict;
my $i="test";
my @tmp=("1","2","3");
writeThis(\@tmp,$i);
.
.
.
sub writeThis(){
  my $tmplocal=shift;
  my $ilocal=shift;

  print "My array: @$tmplocal\n";
  print "My i: ".$ilocal."\n"
}


Trojan.
 
When you pass parameters to a function or subroutine, they are ALL expanded to one long list.
If you use "shift" in your function you would get only one value from that list. If you assign the entire parameter array ("@_") to an array in your function it will slurp all the values from the parameter list and leave nothing for any more parameters to consume.
As you can see from my modified version of your example, the way around this is to pass arrays to functions by reference instead of by value.
Since a reference is only a single value, you can shift it into a single scalar in your function allowing the other parameters to still be assigned as you would expect.

If you need more info, fire another post.


Trojan.
 
One last addition - take the parentheses away from the subroutine definition. Where they are, they'll trigger a warning about prototypes. Just change it to:
Code:
sub writeThis {
   # subroutine code in here
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top