Question

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?

Was it helpful?

Solution

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'};

OTHER TIPS

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

my ($var1, $var2) = test('text1', 'text2');

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'
          }
        ];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top