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

Fwd: [perl #105850] $_ does not work as expected within "given" block

Chris Prather
December 10, 2011 19:15
Fwd: [perl #105850] $_ does not work as expected within "given" block
Message ID:
I missed the list (my apologies David).


---------- Forwarded message ----------
From: Chris Prather <>
Date: Sat, Dec 10, 2011 at 10:13 PM
Subject: Re: [perl #105850] $_ does not work as expected within "given" block
To: David Golden <>

On Sat, Dec 10, 2011 at 7:52 PM, David Golden <> wrote:
> On Sat, Dec 10, 2011 at 6:41 PM, Ricardo Signes
> <> wrote:
>> I agree, *strenuously* that 'given' is a big problem on several fronts, and the
>> lexical $_ is certainly one of the more widely-felt pains.
>> I think fixing it via something like :5.16 containing given5_16 is not nuts,
>> but I've got to say: I think we should be considering deprecating given for
>> straight-up removal.
> I'm supportive only if we replaced it with a decent switch construct
> or deprecated just the broken parts of it.  It doesn't have to be a
> "smart" switch -- just a switch against scalars would be fine.  (Nit
> -- I suppose the challenge is numeric or string matching -- maybe a
> "numeric $scalar" or "string $scalar" keyword like "scalar" for that
> context?)  For anything "smart", we can/should use if/elsif.

Switch and Smart Matching are not equivalent.

I'm guessing (hoping?) that Ric is simply talking about deprecating
`given` and not `when`. Which would leave the more Perl5-ish:

for ($var) {
  when (defined) { ... }
  when (m/foo/) { ... }
  when ($_ eq 'bar') { ... }

That is all you need for switch is a topicalizer (for) and a test that
exits the block on success (when). These cover 99% of the use cases
I've seen in the wild for given/when.

Fact is that I try very hard to only use given/when in cases where I
know it fits within one of the special cases (see above). Removing
given() wouldn't be that painful to most of the code I'm responsible
for, nor honestly would removing SmartMatch. Removing when() however
would make me cry.

>> In the meantime, would we want to consider warning on closing over lexical $_
>> inside a given?  Does anybody ever do this on purpose?
> A warning sounds reasonable and anyone doing it on purpose can turn
> off the warning.

no warnings "given"; # none 'expected';


-Chris Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About