in reply to Re^3: Returning and passing data to and from subroutines
in thread Returning and passing data to and from subroutines

Thanks, the reason I ask is because some how I have done something wrong. When at the programs menu if I were to input lets say "10" it some how returns as a 1 then it fails the test causing my display_menu_error sub to be executed with this error "ERROR: illegal option: 1 selected" some where along the line the 10 I give the program is changed:

db_connect(); #Connect to the database if needed while ( display_menu(), ( my $option = <> ) ) { print '$option before processing input: ' . $option # returns 10 $option = process_input($option); print '$option after processing input: ' . $option # returns 1 if ( ( $option !~ m{/^\d+$/}xms ) or ( $option <= 0 ) or ( $option > +10 ) ) { display_menu_error("ERROR: illegal option: $option selected\n"); next; } print_form() if $option == 1; print_edit() if $option == 2; db_remove() if $option == 3; db_fetch() if $option == 4; print_all() if $option == 5; print_report() if $option == 6; db_check() if $option == 7; leave_comment() if $option == 8; leave_donation() if $option == 9; if ( $option == 10 ) { $dbh->disconnect; print "Quitter...\n"; exit 0; } } ... sub process_input { # takes in information and loops through testing the input for valid a +lphanumeric characters. my @data = @_; for (@data) { chomp; s/^\s*//; # Have tried commenting out no change s/\s*$//; # Still somehow returns incorrect values } return @data; }
I just can't see why it would be doing that to me like that

Replies are listed 'Best First'.
Re^5: Returning and passing data to and from subroutines
by ssandv (Hermit) on Jul 21, 2010 at 15:34 UTC

    Well, one problem you're having is context confusion:

    perl -e 'sub foo {@a=(1,2,4);return @a}; $bar=foo(); print "bar is $bar\n";' bar is 3
    If you want $option to get the _value_, instead of the number of elements in the array, you'll need to either learn about wantarray so your sub knows how it's called, or return a scalar, or do list assignment (which looks like ($option)=process_input($option). Perl is examining @data in a scalar context in your return statement, which gives the number of elements it contains, rather than its contents, because the sub was called as the rvalue of a scalar assignment.