in reply to Subroutine evaluated as boolean

Original poster here.
This is my code (some names have been changed to protect the innocent).
sub searchsub { my ($wanted)=@_; $wanted=extract_value($wanted); for(@$table) { return($_->{VALUE}, $_->{NAME}, $_->{ADDRESS}) if $_->{VALUE} eq + $wanted } () }

So the problem is that it's evaluating ADDRESS instead of the list itself? This would make sense, since the address of the first list is usually 0.
Thank you!

Replies are listed 'Best First'.
Re^2: Subroutine evaluated as boolean
by ikegami (Patriarch) on Oct 13, 2014 at 04:25 UTC
    if ($_->{VALUE} eq $wanted) { return wantarray ? ( $_->{VALUE}, $_->{NAME}, $_->{ADDRESS} ) : 1; }
    or
    if ($_->{VALUE} eq $wanted) { return wantarray ? @$_{qw( VALUE NAME ADDRESS )} : 1; }
Re^2: Subroutine evaluated as boolean (update: hash-slice)
by LanX (Saint) on Oct 13, 2014 at 00:44 UTC
    > So the problem is that it's evaluating ADDRESS instead of the list itself?

    Yes that's the effect if the scalar comma operator.

    Just copy the list to a temporary @array to be returned.

    Or return a literal construct like @{[L,I,S,T]}

    update

    Or best use a hash slice

     return @$_{VALUE,NAME,ADDRESS} if ...

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

      In fact, return @$_{'VALUE','ADDRESS'} has the same problem as my original code. But return @{[@$_{'VALUE','ADDRESS'}]} works great, if it is a little confusing to a beginner like me.
        > return @$_{'VALUE','ADDRESS'} has the same problem as my original code

        yeah sorry, I just tested¹ ...

        ...it's a bit counterintuitive because of the leading @ ... :-/

        > @{[@$_{'VALUE','ADDRESS'}]} works great,

        better don't combine both techniques, readability is more important!

        you could easily do something like

        my @ret=(); for ( @$table ) { next unless $_->{VALUE} eq $wanted; @ret = @$_{VALUE, ADDRESS} } return @ret;

        To get a central exit point.

        update

        > if it is a little confusing to a beginner like me.

        the way context is propagated into subs is always confusing, that's why this was changed in Perl6's design!

        Cheers Rolf

        (addicted to the Perl Programming Language and ☆☆☆☆ :)

        ¹)

        DB<116> $_={a=>1,b=>2,c=>3,d=>0} => { a => 1, b => 2, c => 3, d => 0 } DB<117> sub tst { @$_{a,d} } DB<118> tst() => (1, 0) DB<119> scalar tst() => 0