What is the benefit of Sigils in Perl?

218 Views Asked by At

I understand the rules with sigils. I can make hashes from lists, and pass refs around with the mediocre-ist of them. What I don't understand are the benefits sigils provide in Perl.

Some of the reasons I've heard are:

  • String Interpolation
    • Ruby has the "#{myVar}" syntax, which solves almost all of these issues, including having full expressions without having to resort to the "@{[$count + 1]}" syntactical hack.
  • Readibility
    • IDEs. And any text editor worth its weight in salt has syntax highlighting.
  • Allowing for variable subNamespacing
    • Allowing me to declare $foo and @foo as two different variables will only lead to ruin in the future.

One very helpful feature in a programming language is consistency. My curiosity drives me to ask if I declare a list as "@foos", and a counter "$count", how does it make sense to need to access elements by saying "$foos[$count]"? Oh! But I may use the "@" if I'm reading elements out into list context; so saying "@foos[$idx1, $idx2]" now makes sense! I can tell from looking at the sigil that I'm going to be reading an array instead of a single scalar!

  • I can still tell I'm reading a single element by saying "foos[count]"
  • I can still tell I'm reading multiple elements by saying "foos[idx1, idx2]".
  • I can still tell I'm reading a single value by saying "foos{key}"
  • I can still tell I'm reading multiple values by saying "foos{key1, key2}"

This same pattern holds true for almost any case I can think of. The meaning of what is being done is clear no matter which sigil is being used, or none for that matter. The only difference is that I have to keep track of the context and be sure to keep sigils in line as well;

1

There are 1 best solutions below

3
On

The best explanation is found in perldata in perldoc. They function like articles and pronouns in natural language.

The '$' symbol works semantically like the English word "the" in that it indicates a single value is expected.

Entire arrays (and slices of arrays and hashes) are denoted by '@', which works much as the word "these" or "those" does in English, in that it indicates multiple values are expected.

Perl 6 went a different way, so opinions on their value are varied, but that's the theory behind them.