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

Re: [perl #128678] Wish: 'hard assignment' operator

Thread Previous
Ed Avis
July 20, 2016 14:53
Re: [perl #128678] Wish: 'hard assignment' operator
Message ID:
Dave Mitchell <davem <at>> writes:

>For the cases where it is an error to assign to a non-undef lvalue,
>I would imagine that normally you'd want a specific error message,

It depends.  If validating user-supplied data such as command line arguments,
yes.  But much of the time you are dealing with internal data which you expect
to be unique; the 'die' is expected never to be hit.  (If it is, there is some
logic error in the program which the user wouldn't be able to diagnose.)

It's similar for checks done with the // operator.  For user-supplied data
you want to provide a helpful message:

    my $separator = $opt{separator} // die 'the separator option is required';

But for internal data, where as the programmer you're pretty sure it will
always be set (and want to find out ASAP if your assumption is wrong), it's
easier just to 'die' without much fanfare:

    my $page = $h{page} // die;

Of course, you can start off with the plain 'die;' style for quick hacking
and later improve the error messages.  That is a useful feature of perl, that
it lets you die quickly with a default message if you want.  The hard-
assignment error message could report the name of the variable, its existing
value and the new value that was to be assigned.  That default message
would be good enough in a lot of cases.

So while I would still keep some manual checks in my code for cases that
are catching user mistakes, for the large number of 'not already defined'
checks whose purpose is to catch a programmer mistake, a hard-assignment
operator would cut out a lot of boilerplate.

Ed Avis <>

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