I find this code worrisome because record sometimes returns a hashref and sometimes doesn't, but you don't check which has happened before treating the return value as a hashref. If you haven't use strict'd, you won't hear anything about this; you'll just see corruption later when you try to use $myrecord->{max}. I would strongly recommendsub record{ ($value, $max, $min)=@_; if($value>=$min && $value<=$max){ return{ #returning an anonymous ha +sh value=>$value, max =>$max, min =>$min, }; }else{ return; } } $myrecord=record(100,1000,10); print $myrecord->{max};
(probably with some more informative error message)—as well as use strict'ing, of course.$myrecord = record(100, 1000, 10) or die "That's odd";
By the way, the ternary ?: operator allows you to avoid multiple return statements. In particular, if you did always want to return a hashref, then you could write:
Normally I'd recommend this, but, in this case, it would make you lose the ability to test the return value for falsity.return $value >= $min && $value <= $max ? { value => $value, max => $max, min => $min } : {};
UPDATE: Oops, sorry, <code> ends with </code>, not </c>. :-)
In reply to Re: Simulating user defined data types
by JadeNB
in thread Simulating user defined data types
by biohisham
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |