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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sub parameter gathering -- one liner? 1

Status
Not open for further replies.

Nebbish

Programmer
Apr 7, 2004
73
US
Hey all,

I have a fairly simple issue. I'm passing a subroutine an unknown number of variables in groups of three. For example, I might be passing it:

mySub($hello, 5, $goodbye, 'asdf', 6, 'fdsa');

or

mySub('asdf, 6, 'fdsa');

I figured I'd be slick and arrange the function to take the parameters in groups of three until none were left, using shift:

sub mySub {
while((my $string1, my $dist, my $string2) = (shift, shift, shift)) {
# process
}
}

But, this loops endlessly, even when shift is returning nothing. I'm aware of ways around this, but I'd really like a one-liner if at all possible (some variation of the above while loop?).

Thanks,

Nick
 

Simple:
Code:
sub mySub {
   foreach $argument (@_) {
         # process
   }
}
 
whoops
that wont work, I see your problem. I guess I should have had some more coffee.
 
No, you missed my point: I want to gather the parameters in groups of three, so they fit into $string1, $dist, and $string2 respectively. Your code gathers in groups of one. Does that make sense?

-Nick
 
I think you missed the point nawlej. He wants to handle the args by groups of three.

Code:
doit(1,2,3,4,5,6);

sub doit {
    while(my($a,$b,$c) = splice(@_, 0, 3)){
        print $a,$b,$c, "\n";
    }
}

--jim
 
Nebbish,

I don't have perl here, so I can't give some examples, so it seems to me you could try grouping your variables, as in:

mySub([$hello, 5, $goodbye],['asdf', 6, 'fdsa']);

Your sub will then gen two array values.

Use a foreach to loop on the arrays.




AD AUGUSTA PER ANGUSTA

Thierry
 
Thanks guys...Jim, splice was what I was looking for.

Thierry, not 100% positive, but I believe Perl "flattens" lists and arrays when they are passed into subroutines, so your code would be the same thing as passing it as one big list.

-Nick
 
Thierry's code would have been valid, since he was passing in anonymous arrar references. These are just scalars.

--jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top