Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Re^5: Summing numbers in a fileby Athanasius (Archbishop) |
on Jun 01, 2020 at 07:37 UTC ( [id://11117548]=note: print w/replies, xml ) | Need Help?? |
Do I misunderstand, or is the colliding file handle actually Foo::FH in the example? Yes, that’s correct. The example was intended to show a possible pitfall of using a package global variable instead of a lexical variable. In this example, I would say that the problem is not the use of a global file handle, but the main script placing its code into package Foo and calling frobnicate incorrectly. The use of subroutine prototypes would either make the bug in frobnicate obvious or raise a compile-time error at line 18 when it is called with too many arguments. Well, the idea was that the call to frobnicate was actually what was intended, but the implementation of the subroutine in Foo.pm was erroneous. So if prototypes were used, the sub might well have the correct prototype — sub frobnicate ($) — and then still fail without error or warning. (But anyone using prototypes is strongly advised to familiarize themselves with Far More than Everything You've Ever Wanted to Know about Prototypes in Perl -- by Tom Christiansen first.) But all this is a bit beside the point; I did say the example was “highly contrived.” :-) The point I was trying to make is that variables should — as a rule of good practice — be given the minimum scope needed, and no more.1 Think Defensive programming. Another important principle is this: Wherever possible, prefer compile-time errors to run-time errors.2 If you can make the compiler do your debugging for you, you’ll save both time and effort. So in the case under discussion, by limiting the scope of the filehandle variable you can harness the compiler to check for errors which you would otherwise have to hunt down yourself. In the end, as always in Perl, TMTOWTDI. But, what do you gain by using a package global variable for a filehandle where a lexical variable would do the same job? 1I consider this a corollary of the Principle of least privilege, although strictly speaking that principle has a somewhat narrower focus. [As I was about to post this, I found that haukex had already made a similar case in his excellent reply Re^5: Summing numbers in a file. I’ll post mine anyway, but please read it in conjunction with the post by haukex.] Cheers,
In Section
Seekers of Perl Wisdom
|
|