One letter sub names. When is it a bad idea?

Viewed 60

I had a problem with calling a sub named with just one letter similar to the tests below. And I wasn't able to find some logic to which letters are allowed and not here. Is there any? I see why sub m is a bad idea as it conflicts with m(regex), equivalent of /regex/. But why the others?

Of the tests below subs a, D, E, F are ok. The rest becomes syntax error according to perl v5.26 and v5.30 (the only two versions I checked)

perl -le'sub a{3*pop} print "a: ",a(7)-a(5)'              #prints 6
perl -le'sub b{3*pop} print "b: ",b(7)-b(5)'              #syntax error
perl -le'sub c{3*pop} print "c: ",c(7)-c(5)'              #syntax error
perl -le'sub d{3*pop} print "d: ",d(7)-d(5)'              #syntax error
perl -le'sub e{3*pop} print "e: ",e(7)-e(5)'              #syntax error
perl -le'sub f{3*pop} print "f: ",f(7)-f(5)'              #syntax error
perl -le'sub A{3*pop} print "A: ",A(7)-A(5)'              #syntax error
perl -le'sub B{3*pop} print "B: ",B(7)-B(5)'              #syntax error
perl -le'sub C{3*pop} print "C: ",C(7)-C(5)'              #syntax error
perl -le'sub D{3*pop} print "D: ",D(7)-D(5)'              #prints 6
perl -le'sub E{3*pop} print "E: ",E(7)-E(5)'              #prints 6
perl -le'sub F{3*pop} print "F: ",F(7)-F(5)'              #prints 6
perl -le'sub b{3*pop} print "&b: ",b(7)-&b(5)'            #prints 6
perl -le'sub b{3*pop} print " b: ",b(7)- b(5)'            #prints 6
perl -le'sub m{3*pop} print "m: ",m(7)-m(5)'            #prints 0
1 Answers

Bad idea? Always, pretty much.

What is the problem in this specific case? File test operators. When you write b(7)-b(5), Perl doesn't see a - binary operator and then a function call b(5), it sees the file test operator -b, and then it throws a syntax error because it doesn't make sense to find a file test operator (or any kind of a term) immediately after a function call. There are 27 different letters (some uppercase and some lowercase) used by file test operators.

If you had written b(7) - b(5) then you wouldn't have gotten a syntax error, because -b wouldn't be found in your code... but that doesn't make single-letter names a great idea anyhow.

Related