in reply to Re: Getting the number of times a regexp matches
in thread Getting the number of times a regexp matches

This is an interesting construct, but I don't understand why Perl permits a constant, in this case, the empty list (), to be used in the LHS expression?

For example, the following code spits out an error (Can't modify constant item in list assignment):

(1) = (1,2,3);
so why is the following legal:
() = (1,2,3);
Why is empty list not treated as a constant?

Replies are listed 'Best First'.
(tye)Re2: Getting the number of times a regexp matches
by tye (Sage) on Dec 08, 2000 at 00:39 UTC

    First, because (1) contains a constant (the "1" part) and () contains no constants. So there are no constants being modified so why give an error complaining about you trying to modify no constants.

    Second, as Perl is implemented, I detect a clear preference toward not disallowing things even if the implementor can't think of a good use for that thing at the time. This makes sense for a TIMTOWTDI language.

    Third, we've just demonstrated a use for it. So it is a good thing it wasn't disallowed just because the use wasn't obvious at the time.

    I suspect that this working was at least partially an accident. The list assignment code was written and tested and it worked. I doubt anyone tested this degenerate list assignment. In fact, searching the standard Perl test suite, I find that this feature is not tested but it is used when testing another feature:

    # Should use magical autoinc only when both are strings print "not " unless 0 == (() = "0"..-1); print "ok 14\n"; for my $x ("0"..-1) { print "not "; } print "ok 15\n";
    So there! q-:

            - tye (but my friends call me "Tye")
Re: Re: Re: Getting the number of times a regexp matches
by Fastolfe (Vicar) on Dec 08, 2000 at 00:47 UTC
    I suspect it has something to do with the way these things do work:
    ($a, $b, $c) = (1, 2, 3); ($a, $b) = (1, 2, 3); # 3 discarded ($a, undef, $c) = (1, 2, 3); # 2 discarded ($a, undef) = (1, 2, 3); # 2 and 3 discarded (undef, undef, undef) = (1, 2, 3); # 1 2 and 3 discarded () = (1, 2, 3); # functionally equivalent
    "undef" is the only real non-variable value you can use on the left-hand-side like that.