开发者

How to access array element returned from a object method in perl?

开发者 https://www.devze.com 2023-04-02 17:19 出处:网络
I have been using Perl for a while but is bothered by one syntax problem. In some packages, a method can return an array. For example

I have been using Perl for a while but is bothered by one syntax problem. In some packages, a method can return an array. For example

$root->getlist();

Will return an array. Now I want to get the first element of the result. Of course I can do this:

my @results = $root->getlist();
if($results[0] =~ /wow/) {
    print "Qualified result";
}

However, this is very troublesome. Is there a way that I can combine the first line with second line? I tried this but failed.

if(${$root->getlist()}[0] =~ /wow/) {
    print "Qualified result";
}

Is there a way to do this quick?

A better example: Consider this following package:

package Try;

sub new {
    my $packa开发者_运维百科ge = shift;
    return bless({}, $package);
}

sub getList {
    return (1,2,3,4,5);
}

1;

Now I have a user pl file like this:

use lib '.';
use Try;
use strict;

my $obj = Try->new();
print ($obj->getList())[0];

Trying to run this script will result in:

syntax error at perlarrayaccess.pl line 6, near ")["

Execution of perlarrayaccess.pl aborted due to compilation errors.


if ( ( $root->get_list() )[0] =~ /wow/ ) {
    print "Qualified result";
}


There's wantarray for that. In your sub returning the array, do:

sub getlist()
{
    my $self = shift;

    #  caller wants the full list
    if (wantarray) {
        # fetch all
        return @all_results;
    } else {
        # fetch only first result here.
        return $one_result;
    }
}

This would save you the overhead of fetching all results, when only the one is required. If it's another index you specifically need, write:

if ([$root->getlist]->[5] =~ /wow/) {
...
}

I know, perl is not about easy reading, but this one's more legible than ${$root->get}[0].


if($root->getlist()[0] =~ /wow/) {
    print "Qualified result";
}

Ought to work. The second thing that you tried treats the returned value as an array reference and tries to dereference it. The method just returns an array (or rather, a list - there is a difference), so you need to just access the element you want.


Using Perl syntax you can just assign return value to a list of variables:

my ($result) = $root->getlist();
print "Qualified result" if $result =~ /wow/;

This is very basic Perl syntax that often used when you need to get few parameters in sub:

sub get_three_params {
    my ($foo, $bar, $baz) = @_;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消