Aelfhere Aelfhere - 7 months ago 18
Perl Question

Passing arrays in Perl

All right, I'll try to explain what I've done so far. I'm using a Parellel::ForkManager to grab data from an array of URLs, which is then stored in variables (value1, value2, value3).

I then collect the data from all of those processes, and display the data with

$pm->run_on_finish
.

#...
my $pm = new Parallel::ForkManager(10);

$pm->run_on_finish (
sub {
my @info = @{$data_structure_reference};

print $info[0];
print $info[1];
print $info[2];
}
);

for my $var (@urls) {

$pm->start and next;
#...
@returned = &something($var);
#...
$pm->finish(0, \@returned);

}

sub something {

#... getting data from each URL and storing it in variables

my @array = (
$value1,
$value2,
$value3
);
return @array;
}


Now, what I want to do, is to pass an array,
@value4
, as well, and then only display that data if there is something in the array. So, I want it to look like this:

sub something {

#... getting data from each URL and storing it in variables

my @array = (
$value1,
$value2,
$value3,
@value4
);
return @array;
}


And then I want it to print that array, only if there is something in it.

Unfortunately, I'm not entirely sure how to go about doing that.

TLP TLP
Answer

I assume that what you are asking is how to return an array along with the three scalars returned from the something() sub, and print it?

I also assume that those three scalars are what's referred to as being in @info.

The simplest way seems to me to be to simply tack them to the end of the array you return, use the three first values, and if there's anything left, print that too.

$pm->run_on_finish (
    sub {
        my @info = @{$data_structure_reference};

        print splice @info, 0, 3;
        print @info if (@info);
    }
);

sub something {
    return (
            $value1,
            $value2,
            $value3,
            @value4
        );
}

As you'll notice, you do not need to fill a dummy array for the return value, simply return values inside the parens. You do not need to dereference the array, since you can use the @info array straight up if you splice off the first three values.

I like it simple. If it works.

Comments