On Sun, Jan 15, 2017, 16:19 <al...@myfastmail.com> wrote: Hi,
On Sun, Jan 15, 2017, at 01:01 PM, Shawn H Corey wrote: > > Is there a different, recommended way? > > Nothing's wrong. perlcritic does not this valid method, that's all. > > TIMTOWTDI (There Is More Than One Way To Do It.) Hm, ok. As long as it's not wrong/broken in some weird way. I kept getting scolded to "check your code with perlcritic" as if that's the *right* way to do it. So when I kept getting that perlcritic-ism, I started looking around for why. LOTS of post telling you different things NOT to do, but nothing that explained in a way I could understand why what I was doing wasn't cool. I must've read & parsed that "--verbose 11" output a dozen times. Just isn't understandble :-( So, anyway, sticking with what I got until if/when I understand the point! Thanks alot. AJ In this case, what you are doing "wrong" is trusting the caller of the function. Good defensive practices will save you a ton of headache in the future. Your code expects the first (and only) argument to be a hashref. Proper checking of the arguments will save maintainers tons of time. For instance, examine these error messages: Can't use string ("FN") as a HASH ref while "strict refs" in use at sig.pl line 9. Not a HASH reference at sig.pl line 9. And now look at these error messages: wrong number of arguments at sig.pl line 13. main::better("FN", 1, "AR", 1, "AD", 1, "DR", 1) called at sig.pl line 34 eval {...} called at sig.pl line 36 argument isn't a hashref at sig.pl line 15. main::better(ARRAY(0x7fc08b0292a8)) called at sig.pl line 41 eval {...} called at sig.pl line 43 These error messages were produced by the following code. In both cases (calling with a list instead of a hashref and calling with an arrayref instead of a hashref), the first set of error messages only tell you where the code blew up, not where the programmer made an error. In the second set of error messages, you get better location information and better overall information. Now, this is obviously better for the maintainer, but it comes at the cost of more verbose code. If this is a one-off script, then it probably isn't worthwhile; however, if this is code that is meant to live for any appreciable length of time, then verbode handling is best. #!/usr/bin/perl use strict; use Carp; use warnings; sub not_so_good { my %args = %{ shift @_ }; } sub better { croak "wrong number of arguments" unless @_ == 1; my $arg = shift @_; croak "argument isn't a hashref" unless ref $arg eq ref {}; my %args = %$arg; } eval { not_so_good(FN => 1, AR => 1, AD => 1, DR => 1); 1; } or do { print "got error: $@"; }; eval { not_so_good([FN => 1, AR => 1, AD => 1, DR => 1]); 1; } or do { print "got error: $@"; }; eval { better(FN => 1, AR => 1, AD => 1, DR => 1); 1; } or do { print "got error: $@"; }; eval { better([FN => 1, AR => 1, AD => 1, DR => 1]); 1; } or do { print "got error: $@"; };