billh has asked for the wisdom of the Perl Monks concerning the following question:
and a value() method that converts the linked list to a perl list:{ rest => $next_node, first => $data }
The reason I need the temporary @value is that sometimes value() gets called in a scalar context in which case it should return the length of the list, but if I was to just writesub value { my ($self) = @_; my @value = ($self->{first}, $self->{rest} ? $self->{rest}->value : ()); return @value; }
then in a scalar context the "," gets interpreted as the comma operator and the lhs of the comma gets thrown away, recursively, so the result is always zero.sub value { my ($self) = @_; return ($self->{first}, $self->{rest} ? $self->{rest}->value : ()) }
I guess I could also write:
but neither solution seems totally satisfying.sub value { my ($self) = @_; return @{[$self->{first}, $self->{rest} ? $self->{rest}->value : ()]}; }
Am I missing something?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: enforcing list context
by japhy (Canon) on Apr 26, 2006 at 11:24 UTC | |
by billh (Pilgrim) on Apr 26, 2006 at 12:53 UTC | |
|
Re: enforcing list context
by BrowserUk (Patriarch) on Apr 26, 2006 at 10:42 UTC | |
by billh (Pilgrim) on Apr 26, 2006 at 11:11 UTC | |
by BrowserUk (Patriarch) on Apr 26, 2006 at 11:37 UTC | |
|
Re: enforcing list context
by duff (Parson) on Apr 26, 2006 at 11:38 UTC | |
by japhy (Canon) on Apr 26, 2006 at 11:46 UTC | |
by duff (Parson) on Apr 26, 2006 at 12:19 UTC | |
|
Re: enforcing list context
by TedPride (Priest) on Apr 26, 2006 at 17:18 UTC | |
by billh (Pilgrim) on Apr 26, 2006 at 20:38 UTC | |
|
Re: enforcing list context
by diotalevi (Canon) on Apr 26, 2006 at 20:50 UTC | |
by billh (Pilgrim) on Apr 26, 2006 at 21:00 UTC |