perl-diddler has asked for the wisdom of the Perl Monks concerning the following question:
I'd like to have a class sub 'Arr', that if passed a param, it would return $p->{Arr}$param,
ELSE, I'd like it to return @$p-{Arr}, in such a way that if I'm using it in a scalar context, it gives me the # of elements in that array, but if I used it in a context needing a reference, like push @{$p->{Arr}}, "val", it would 'do the right thing'...
I can create an ugly hack where I can force it to return a ref, by using 'wantarray', to send it the message and use "push @{($p->{Arr},)[0]},val", -- and to get the scalar context, always be sure to put in 0+$p->{Arr}, but that's is a seriously ugly and special-cased hack. What I really want is a 'wantref' function that I can use in the 'Arr' func to determine whether or not to pass back the ref or not.
Originally I had:
sub Ts { $_[1] ? $_[0]->{Ts}[$_[1]] : $_[0]->{Ts} }
(Note: 'subname' 'varies', I used 'Arr' for the general case in my description). That didn't do anything good...in a printf "%d", $p-{Arr}, it always returned '1' (even though the array had 3 elements). To get that i had to use:
sub Ts { $_[1] ? $_[0]->{Ts}[$_[1]] : 0 + $_[0]->{Ts} }
Of course that doesn't work for the ref... Then I tried the ugly hack:
sub Fans { $_[1] ? $_[0]->{Fans}[$_[1]] : wantarray ? $_[0]->{Fans}:0+@$_[0]->{Fans} }
That does what I described above under 'ugly hack'...i.e. I can get the ref back and use it in push by embedding it a list, and get the #elements back by adding '0' to it where I call it...
So how do I get it to work without the "smarmy" syntax...i.e. get a func that returns a ref or a scalar depending on how it's called?
Is there a 'wantref' func that I don't know about that has some odd name?
Thanks!
p.s. Hey, what's with P.M. not recognizing &;GT; in code and xlating it to ">"? Doesn't HTML convert text entities everywhere?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to determine if 'ref' is wanted? (ala 'wantarray')
by ikegami (Patriarch) on Nov 07, 2011 at 02:00 UTC | |
by perl-diddler (Chaplain) on Nov 07, 2011 at 19:58 UTC | |
by ikegami (Patriarch) on Nov 07, 2011 at 21:30 UTC | |
|
Re: How to determine if 'ref' is wanted? (ala 'wantarray')
by anneli (Pilgrim) on Nov 07, 2011 at 01:08 UTC | |
by perl-diddler (Chaplain) on Nov 07, 2011 at 19:36 UTC | |
by chromatic (Archbishop) on Nov 07, 2011 at 20:33 UTC |