in reply to Simulating user defined data types

sub 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};
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 recommend
$myrecord = record(100, 1000, 10) or die "That's odd";
(probably with some more informative error message)—as well as use strict'ing, of course.

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:

return $value >= $min && $value <= $max ? { value => $value, max => $max, min => $min } : {};
Normally I'd recommend this, but, in this case, it would make you lose the ability to test the return value for falsity.

UPDATE: Oops, sorry, <code> ends with </code>, not </c>. :-)

Replies are listed 'Best First'.
Re^2: Simulating user defined data types
by biohisham (Priest) on Aug 08, 2009 at 17:37 UTC
    O yeah, I got it, I am thinking of working more with references than to worry about what a user-defined-data type is, I googled it up and guess what, I get this node in the search results returned back to me, the other results out there did not address the issue quite from this perspective so it was perplexing...

    so I am like let it lay low for a little while and I'd come back at it with sharper filed teeth :P..

    with regard to ternary operator, I am cool with it, and to that end I would use it ..thanks for the support everyone and thanks YourMother, you're there as usual :) _________________________________________________________________________
    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind