develooper Front page | perl.perl5.porters | Postings from July 2003

Re: (func()){key}?

Thread Previous | Thread Next
Stephen McCamant
July 30, 2003 22:30
Re: (func()){key}?
Message ID:
>>>>> "MGS" == Michael G Schwern <Michael> writes:

MGS> I'm sure this has come up before, but I'm curious.  Why doesn't
MGS> this DWIM:

MGS>     sub foo {
MGS>         return( this => 42, that => 23 );
MGS>     }
MGS>     $this = (foo()){42};

MGS> Similar to:

MGS>     sub foo {
MGS>         return(42, 23);
MGS>     }

MGS>     $this = (foo())[1];

I think the reason the parallel you're suggesting doesn't work is that
despite its use of square brackets, which is confusing, the (...)[...]
operator (where the parens are mandatory, note) doesn't have anything
to do with arrays: it's a *list* slice.

The (...)[...] list operator exists because "give me the 7th element"
is an operation that makes sense on a list as well as on an array; if
this is imposing an array structure on the list, it doesn't seem like
much of an imposition. Your suggested (...){...} operator seems less
sensible to me because performing a hash operation on a list is more
of a stretch ("give me an odd-indexed member of this list such that
the preceding element is 'foo'").

Off hand, I can't think of a syntactic problem with allowing
(...){...} parallel to (...)[...]. I'm not sure what a good
implementation would be, though. A list is a bunch of scalar values on
the stack, and the indices would also turn into a list, so you'd want
to do a list-list intersection. The asymptotically efficient way to do
this would be to turn one of the lists into a hash table, but as you
noted in another message, we can already do that explicitly by
rewriting (foo){bar} as {foo}->{bar} (or @{foo}{bar} if you want a
multi-element slice). You could do a separate linear search for each
index, but that would have the danger of being unexpectedly slow for
large slices.

Historically, I don't know if it would have been necessary to add
(...)[...] to the language if [...]->[...] had been around at the
time. Given that we now have {...}->{...}, and there isn't a better
implementation we could use for (...){...} (unless we limited it to
single elements, which would break the parallel), I don't see much
call for it.

 -- Stephen

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About