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?
In reply to enforcing list context by billh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |