develooper Front page | perl.perl5.porters | Postings from July 2011

given XOR grep is evil

Thread Next
From:
Paul LeoNerd Evans
Date:
July 26, 2011 12:12
Subject:
given XOR grep is evil
Message ID:
20110726191157.GB18032@cel.leo
One of given() or grep() is doing something strange here:

  $ cat foo 
  #!/usr/bin/perl

  use feature qw( say switch );
  use List::MoreUtils qw( any );

  foreach(1) {
    when(/\d+/) {
      say "foreach/grep OK" if grep { $_ == 2 } 2;
      say "foreach/any  OK" if any  { $_ == 2 } 2;
    }
  }

  given(1) {
    when(/\d+/) {
      say "given/grep OK" if grep { $_ == 2 } 2;
      say "given/any  OK" if any  { $_ == 2 } 2;
    }
  }

  $ perl foo
  foreach/grep OK
  foreach/any  OK
  given/grep OK

Where did given/any go?

Actually, I half-know the answer to this question. given() creates a
lexical $_ whereas foreach() just locally modifies the global one. This
explains why foreach and given differ.

But what about any vs. grep? What is grep doing special here, that any
isn't?

I am currently not quite able to decide what the ideal behaviour ought
to be.

 1. Print OK for all four combinations?

 2. Fail to print OK for either 'given' combination?

I find the current behaviour distasteful, either way you look at it.


Thoughts?

PS: See also https://rt.cpan.org/Ticket/Display.html?id=46754

-- 
Paul "LeoNerd" Evans

leonerd@leonerd.org.uk
ICQ# 4135350       |  Registered Linux# 179460
http://www.leonerd.org.uk/

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About