passing arguments to subroutines

Discussion in 'Perl Misc' started by Roman Rodriguez, Aug 29, 2004.

  1. Can anyone tell me if you can pass scalars and list to subroutines? if so,
    what is the syntax? what am I doing wrong in the following code?
    It seems the correct value is not returned because my subroutine doesn't
    appear to be recieveing the parameter from the caller.


    sub setMainMenuOption
    {
    my $SelectedOption = $_; #set $SelectedOption to value passed in
    (from user)
    if( $SelectedOption eq 's')
    {
    return("Sleep");
    }
    return("INVALID");
    {
    $UserInput = "S\n"; #simulate STDIN user input of the capital letter 'S'
    print "\n\$UserInput: $UserInput";

    chomp($UserInput);
    print "\n\$UserInput after CHOMP: $UserInput";

    $UserInput = lc($UserInput);
    print "\n\$UserInput after lc(): $UserInput";

    $Menu = &setMainMenuOption($UserInput);
    print "\n\$Menu after return = $Menu";

    exit;

    results in the following output:

    $UserInput: S
    $UserInput after CHOMP: S
    $UserUnput after lc(): s
    $Menu after return = INVALID

    when I step through this code I see that "$_" in the subroutine is not
    properly recieving the arguement and therefore variable $SelectedOption is
    remaining as "".
    what is the proper way to pass arguments to a subroutine?

    Thanks!
    -RR



    Thanks
    -RR
     
    Roman Rodriguez, Aug 29, 2004
    #1
    1. Advertisements

  2. You can.
    It's described in "perldoc perlsub".
    Arguments that are passed to a sub are available within the sub in @_,
    not in $_.
     
    Gunnar Hjalmarsson, Aug 30, 2004
    #2
    1. Advertisements

  3. ^
    This should be a right curly!
    No it does not!
    There should be an empty line here
    Not that it matters in this case, because the answer to the question was
    very obvious, but the incorrect reproduction of the source and the
    results may confuse people who are willing to help!

    Best to use copy-and-paste when posing code and results rather than
    typing them in.
     
    Josef Moellers, Aug 30, 2004
    #3
  4. perldoc perlsub
    perl is saying:
    Missing right curly or square bracket at C:\tmp\t.pl line 24, at end of
    line
    That means your curly brackets are not balanced.

    [code snipped]

    jue
     
    Jürgen Exner, Aug 30, 2004
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.