http://qs321.pair.com?node_id=436925


in reply to looking for a good idiom: return this if this is true

I want a subroutine to call another subroutine, and if the return value from that subroutine is true, this subroutine should return that value, otherwise continue.

I'd think that keeping value retrieval and flow of control separate will be easiest on whoever picks up the code next. That speaks for either of your last two solutions, or something more explicit, like

my $v = thatroutine(); return $v if $v;

Since you're willing to consider taking on the overhead of eval, I rather suspect a temporary variable won't faze you, especially since it offers a convenient debug point for anyone who is stepping through the code.

Replies are listed 'Best First'.
Re^2: looking for a good idiom: return this if this is true
by merlyn (Sage) on Mar 05, 2005 at 19:37 UTC

      Huh? Are you confusing ...

      No confusion here. The bookkeeping overhead (pushing a marker onto the return stack, though I recall eval doing a bit more than that) is on par with creating a temporary variable. In my mind, at least, that cancels any performance objections about using a temporary variable.

      eval'ing a string would be nuts, and I give you credit for not being that nuts.

Re^2: looking for a good idiom: return this if this is true
by wolfger (Deacon) on Mar 07, 2005 at 14:46 UTC

    why not just:

    retrun thatroutine() if thatroutine()

    edit: or

     if (thatroutine()) {return $_}

    --
    Linux, sci-fi, and Nat Torkington, all at Penguicon 3.0
    perl -e 'print(map(chr,(0x4a,0x41,0x50,0x48,0xa)))'
      retrun thatroutine() if thatroutine()
      That calls thatroutine() twice, which will perform things twice. Not good.
      if (thatroutine()) {return $_}
      $_ isn't getting set there. Are you expecting the variable to be psychic?

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

        if (thatroutine()) {return $_}
        $_ isn't getting set there. Are you expecting the variable to be psychic?

        No, I'm not expecting that. I tested this with a one-liner prior to posting, I swear. Problem is, I just tried re-entering that one-liner prior to posting my proof here and.... It doesn't work. I suppose I must have screwed that up somehow, the first time around. I'm not entirely clear on how $_ works.


        --
        Linux, sci-fi, and Nat Torkington, all at Penguicon 3.0
        perl -e 'print(map(chr,(0x4a,0x41,0x50,0x48,0xa)))'