in reply to The trouble with Perl Idiom

That reads awkwardly, I find. This is how I'd write it:

sub getRef { my $self = shift; $_ = $self->getNodeById( $_ ) for grep { $_ and not ref } @_; return ref $_[0]; }

It maps more closely to the way I think of the problem. You can almost read it out in natural language: "filter it through $self->getNodeById() for every element that is true and not a reference".

Makeshifts last the longest.

Replies are listed 'Best First'.
Re^2: The trouble with Perl Idiom
by demerphq (Chancellor) on Aug 29, 2004 at 22:10 UTC

    I almost never chain grep together with another looping structure. I see no reason to iterate lists twice.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi


      That is an implementation detail. :-)

      Remember, code is written primarily for programmers to read and only incidentally for a machine to execute. Did you profile this and found it to be a problem?

      NB: I quarreled with the thought of adding a note to the effect that this construct loops twice on my previous node, but decided against it. The typical data set in this function would consist of one element, or of less than 10 elements in most other cases. Musing about its efficiency therefore seems like a rather pointless excercise.

      Makeshifts last the longest.

        Musing about its efficiency therefore seems like a rather pointless excercise. </code>

        I just don't see the point in looping twice when a single loop will do. Each loop has its overheads regardless of how many elements are involved, so why incur them twice when the readability gain is low? In fact IMO a lot of maintenance programmers won't even know what 'grep' does but will probably guess correctly what 'next if' does. So you aren't really improving readability for the price of a definite efficiency loss.

        I've only seen one or two situations where I felt 'for grep' or 'map grep' made much sense. *shrug* :-)


        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi