0

There's already an answer for why my % foo; or my $ string; both compile in perl, but I was surprised to see that this is also the case when the variable name is itself a function, such as split:

use warnings;
use strict;

my $ split = 'why does this work?';

say $split;
# why does this work?

How can this be the case?

Community
  • 1
  • 1
fugu
  • 6,417
  • 5
  • 40
  • 75
  • 3
    Same reason that `$split` works. Being preceded by a sigil is significant, being immediately preceded by one is not. The whitespace is irrelevant there. – Quentin Jul 14 '16 at 12:45
  • 1
    If you want to know the nitty-gritty details, it all happens in [toke.c](https://github.com/Perl/perl5/blob/v5.24.0/toke.c), perl's lexer. In `perl -e'$ split'`, when the lexer encounters `$`, it checks for a bunch of different things like `$#`; if none of those things match, it says that the next token must be an identifier, so `split` is treated as an identifier, not a keyword. In `perl -e 'split'`, when the lexer encounters `s`, it does a keyword lookup and finds a match, so `split` is treated as a keyword. See lines 5293 and 6225 in the version of toke.c that I linked. – ThisSuitIsBlackNot Jul 14 '16 at 17:33

0 Answers0