Why is the Switch module deprecated in Perl?
Why was the Switch module deprecated in Perl 5.12?
I know 开发者_Go百科that a switch
/case
be made with elsif
, but I don't like that very much.
Perl 5.10 introduced a real switch called given-when
The old Switch used source filtering and had other limitations.
The original Switch uses a source filter to do its work, and that's often a bad idea. Essentially, it pre-processes your literal source to create new code before perl compiles it. The module was never really intended to be heavily used, and it was more of a proof of concept to figure out what a real Perl feature could look like.
Perl 5.10 added the given-when
construct to do what most people want from a switch-case
, but it does quite a bit more. Learning Perl, 5th Edition devotes an entire chapter to it along with smart matching. However, in Learning Perl 7th Edition we removed that chapter since smart-matching is experimental as of v5.18.
You can't make a Perl given-when
with the if-elsif-else
constructs. given-when
lets you execute multiple blocks and well as add interstitial code. With if-elsif-else
you execute exactly one branch.
First of all, Switch is not deprecated. It's inclusion in core was deprecated in 5.12. All that means is that while Switch was bundled with Perl 5.8 and 5.10, it isn't bundled in Perl 5.14 and newer. It does NOT mean people should stop using the module. The module may still be installed from CPAN separately from perl
.
Mind you, many including myself advise others to avoid using Switch, but that's independent of its deprecation from core, and it far predates 5.12. Using Switch can lead to very odd and hard to debug errors because it modifies your code before Perl sees it, all while providing minimal benefit if any at all.
For that reason, and because Perl started offering a native alternative (given
-when
), it was decided that Switch would no longer be bundled with perl
.
Unfortunately, given
-when
has problems, and was retroactively marked as experimental in 5.18. It isn't safe to use these as they will be changed in a backwards-incompatible manner (or maybe removed) in the future.
精彩评论