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

here's my question: i want to have a sub function which takes 3 variables in, say they are
my($a,$b,$returnstring) = @_; i want to put $a and $b into $returnstring so that if $a= hel and $b= +lo, then $returnstring= 'hello' and return $returnstring;
is this possible?

Replies are listed 'Best First'.
Re: sub functions, and strings
by DigitalKitty (Parson) on Nov 11, 2002 at 21:02 UTC
    Hi bdawg613.

    I hope this is what you meant:

    #!/usr/bin/perl -w use strict; my ( $str1, $str2, $c, $rs ); $str1 = 'hel'; $str2 = 'lo; $c = &concat( $str1, $str2 ); print "$c\n"; sub concat { my( $a, $b, $rs ) = @_; $rs = $a . $b; return $rs; }


    You could also read the input ( $str1, $str2 ) from STDIN if you wanted to. There are much easier ways of writing this program though. If you need help, just ask.

    Hope this helps,
    -Katie.
Re: sub functions, and strings
by nedals (Deacon) on Nov 11, 2002 at 22:25 UTC
    Am I missing somethig? I assume that '$returnstring' is what you want back. In which case it should not be in the argument list. The code to do this is simply...
    sub getString { my ($a,$b) = $@_; return "$a$b"; # OR return $a.$b; } #usage... my ($str1, $str2); my $returnstring = &getString($str1,$str2);
Re: sub functions, and strings
by dmitri (Priest) on Nov 11, 2002 at 20:48 UTC
    If you return concatenated first and second argument, why pass a third argument to the function? If you want to pass the third argument "by reference," pass a reference to the scalar (remember that Perl only passes parameters by value). Then you will be able to say something like
    $$returnstring = $a . $b;

    Also, you might want to re-phrase your question.

      Perl doesn't exactly pass by value -- you can modify the calling arguments by monkeying with the values of @_.

      All that seems needed here is :
      sub concat { join '', @_ } my $joined = concat( $first_part, $second_part );


      Updated to remove misplaced rant about symbolic references - see below.
        Why the symbolic reference?
        Huh? He didn't say anything about symbolic references. He said "references", and his illustration was as valid for hard references as symbolic ones.

        jdporter
        ...porque es dificil estar guapo y blanco.