Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
I wrote a piece of code which works fine when included in script.
But behaves differently when I put in the subroutine. The code in the script and in sub routine follows:
my($Records); foreach $Records(@EventList) { if($Records =~ /(.*)(\,)(.*)/) { if($Records ne $eventChoice){ print "<option value='$Records'>$3</option>\ +n"; } } } &PopulateEventDropDown(@EventList,$eventChoice); sub PopulateEventDropDown { my($Records); my $eventChoice = shift; my @Records = @_; foreach $Records(@Records) { if($Records =~ /(.*)(\,)(.*)/) { if($Records ne $eventChoice) { print "<option value='$Records'>$3</option>\n" +; } } } #end foreach }
Here on the script option values are printed correctly without $eventChoice values.
But when called from the subroutine it prints the $eventChoice as usual and also adds it to the end.
What is the worng with the code.

Thanks
Blazix

Replies are listed 'Best First'.
Re: where is the error ??
by wufnik (Friar) on Jul 27, 2004 at 19:06 UTC
    dude, it's simple. you have your args the wrong way round in your sub.

    ie: change the arg pick up code in the sub to:
    my $eventchoice = pop @_; my @records = @_;
    or something.
    ...wufnik

    -- in the world of the mules there are no rules --
Re: where is the error ??
by calin (Deacon) on Jul 27, 2004 at 19:06 UTC

    Try to reverse the order of the arguments in your subroutine call, and see if it helps:

    &PopulateEventDropDown($eventChoice,@EventList);

    instead of:

    &PopulateEventDropDown(@EventList,$eventChoice);
Re: where is the error ??
by ysth (Canon) on Jul 28, 2004 at 08:24 UTC
    shift removes things from the start of the array (@_ or @ARGV is the default array, containing the sub or the script's parameters). If you pass the $eventChoice last, you need to use pop instead.