develooper Front page | perl.perl5.porters | Postings from April 2018

Re: [perl #133109] push on scalar forbidden: why?

Thread Previous | Thread Next
L A Walsh
April 21, 2018 21:10
Re: [perl #133109] push on scalar forbidden: why?
Message ID:
Dave Mitchell wrote:
> But when you have a scalar reference which is overloaded, perl can't know
> what overload method to call in those cases. For example:
>     use overload
>         '@{}' => sub { print "array deref\n" ; return \@real_a },
>         '%{}' => sub { print "hash  deref\n" ; return \%real_h },
>         ;
>     my $r = bless [];
>     push $r, 3;        # prints "array derdef", modifies @real_a
>     $r->{foo} = 'bar'; # prints "hash  derdef", modifies %real_h
>     @k = keys $r;      # what overload method does this call?
> What should perl do in the last case?
Two answers.  The first answer: it never gets that far.

PERL5OPT="" perl /tmp/
Not an unblessed ARRAY reference at /tmp/ line 9.

2nd answer -- this was brought up by Dan Brook.  I answered:

-------- Original Message --------
Date: 	Fri, 13 Apr 2018 18:47:08 -0700
From: 	L A Walsh

Dan Book wrote:

> One of the biggest problems with it is that there's no correct 
> way to handle an object with both hash and array overloads defined.
I disagree, in so much as if there is ambiguity, it is IMO, inherently an
error (incomplete specification) -- the computer cannot infer proper
function by context.
---- end Message -----

In any case where there is ambiguity, the compiler must throw an error(like):

Ambiguous dereference @ line 13: Sigil required.

My suggestion was to auto-dereference references where perl knew the type
of the reference.  If it reference is ambiguous, it can't know the type.

The 2nd part was to allow a scalar that holds 'undef' to be
auto-vivified where only 1 solution would work.  I.e.

my $ref
push $ref, 1;

would autovivify a temporary array pointed to by '$ref', as push requires
an array.

my $ref;
my $val=pop $ref;

would act identically to:

my $val=pop @$ref;

Any case where perl has an ambiguous choice, must be flagged as an
error.  I can't see any other option being correct.

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