-1

I have this

sub test
{
my ($arg1, $arg2) = @_;  # Argument list
code
return ($variable1, $variable2);
}

So, when i call this by

test('text1','text2');

concatenates the two return values in one. How can i call only one at a time?

Martzy
  • 85
  • 12
  • 2
    Please describe you question clearly. – zdd Mar 16 '14 at 01:39
  • I want to call this sub with two output choises, first with the output of variable1 and second with output of variable2. Something like test('text1','text2') -> variable1 and test('text1','text2') -> variable2 – Martzy Mar 16 '14 at 01:43
  • 2
    I am sorry, I still don't understand what do want, hope someone else know that. – zdd Mar 16 '14 at 01:58
  • 1
    @Martzy I think you would want to pass in another variable that specifies whether you want to return `variable1` or `variable2`, and then return the proper one based on that. You could modify `test` to do this or create a new subroutine that calls `test` and picks which one to return. – hmatt1 Mar 16 '14 at 02:21

3 Answers3

1
my $output_choice_1 = ( test('text1','text2') )[0];
my $output_choice_2 = ( test('text1','text2') )[1];

or both at once:

my ( $output_choice_1, $output_choice_2 ) = test('text1','text2');

Though sometimes it makes for clearer code to return a hashref:

sub test {
    ...
    return { 'choice1' => $variable1, 'choice2' => $variable2 };
}
...
my $output_choice_1 = test('text1','text2')->{'choice1'};
ysth
  • 96,171
  • 6
  • 121
  • 214
0

Are you asking how to assign the two values returned by a sub to two different scalars?

my ($var1, $var2) = test('text1', 'text2');
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

I wasn't really happy with what I found in google so posting my solution here.

Returning an array from a sub.

Especially the syntax with the backslash caused me headaches.

#!/usr/bin/perl

use warnings;
use strict;

use Data::Dumper;

sub returnArrayWithHash {
  (my $value, my %testHash) = @_;

  return ( $value, \%testHash );
}

my %testHash = ( one => 'foo' , two => 'bar' );

my @result = returnArrayWithHash('someValue', %testHash);

print Dumper(\@result) . "\n";

Returns me

$VAR1 = [
          'someValue',
          {
            'one' => 'foo',
            'two' => 'bar'
          }
        ];
Amanda
  • 194
  • 1
  • 11