in reply to A new user question on OO Perl

You probably don't need the parentheses on the right side of the expression; they're superfluous. The parentheses on the left side put the entire expression into list context. The get_list method probably returns a list, which when evaluated in scalar context will give you something besides the first element of the list.

In list context, you'll get the first element of the list, which is presumably what you expect.

This is all just a guess though; we'd have to see the code in get_list to tell you for sure.

Replies are listed 'Best First'.
Re^2: A new user question on OO Perl
by Anonymous Monk on Dec 19, 2007 at 05:57 UTC
    Hi, Here is the get_list method in Data::Container package:
    sub get_list { my ($self, @capwords) = @_; my $items = $self->{items}; my @list = (); return @list unless $items; foreach my $item (@{$items}) { push @list, $item if ($item->is(@capwords)); } return @list; }

    The get_list does return an array.
    Thanks for the hint you provided. I understand it now better.
    One final question though. In the package Library, I have the following:
    sub get_list { my ($self, @keywords) = @_; return $self->{lib}->get_list(@keywords); }

    The method Library::get_list will actually return the result of Data::Container::getlist. Is my understanding correct?
    --Jess

      As to your final question, if $self->{lib} contains a Data::Container object, then the method will return the result of the get_list method on that object.

      You could rewrite your get_list method to behave appropriately in scalar context with:

      sub get_list { my ( $self, @capwords ) = @_; # return nothing in void context return unless defined wantarray; # return nothing if there are no items return unless $self->{items}; # return filtered list in list context return grep { $_->is( @capwords ) } @{ $self->{items} } if wantarr +ay; # return the first filtered element in scalar context for my $item ( @{ $self->{items} } ) { return $item if $item->is( @capwords ); } # explicitly return nothing if there's no filtered list return; }

      The important thing to learn from this is wantarray, thought you might also like to know that return with no expression returns an empty list in list context and undef in scalar context.