in reply to Lexical $_ in given/when vs. BLOCK arguments

I think you are right, and it's a known bug. However the RT search "helpfully" gave me no results when searching for "given", even though I know of at least one ticket with "given" in the title (unrelated to your question though).

  • Comment on Re: Lexical $_ in given/when vs. BLOCK arguments

Replies are listed 'Best First'.
Re^2: Lexical $_ in given/when vs. BLOCK arguments
by mbethke (Hermit) on Oct 25, 2011 at 18:06 UTC

    I have to admit I didn't even search because after a look at the trivial code of any() (and pasting it in my script to make sure it's not the fault of some XS foo) I was pretty convinced it can't possibly be the function's fault. It's written exactly as I would do it and as every book I've seen recommends it.

    Thanks to everybody who recommended "our" etc.---I'd only tried local which unsurprisingly didn't work. Still, having to think about something like this is a major PITA, particularly when it's inconsistent and e.g. works with builtins like grep. I think for me it boils down to "given is evil". for/when should do fine as long as there are no continues.

    List::* and similar modules could probably work around that with some bytecode hack as suggested in a reply to the bug but having to introduce such extreme ugliness to restore sane behavior suggests something else needs fixing

    So I think this is at least a documentation bug of given/when. Why the lexical $_ I still don't know; making

    given($foo) { when('bar') { ... } }
    equivalent (well, with some added magic for the last/continue stuff) to
    do { if($foo ~~ 'bar') { ... } }
    would seem to make more sense IMHO. But if it behaves like it does, it should carry a big fat warning saying "If you define any blocks or callbacks within given(), don't expect $_ to behave like everywhere else, use explicit "our" or there will be weeping and gnashing of teeth!!!11!"

      I think for me it boils down to "given is evil".

      I concur. I tried to use given/when on a few occasions and always reverted to something simpler. Altogether just to damn magical for its own good. I seriously doubt I will ever make use of it again.

      I much prefer the simple, reliable semantics of use Switch::Perlish 'C';


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.