Tuesday, June 30, 2009

Perl is truly weird

Otherwise how else would you treat the following: $#$ar_ref?

It is actually $#($ar_ref) which is the last index of an array referenced via $ar_ref.

3 comments:

Hercynium said...

It's actually not that weird...
Since there is special "sigil" to get the index of the last element in an array, doesn't it make sense that you can apply that sigil to a reference to that same array and get the same result?

Also, the version you posted with the parenthesis is incorrect. In this case, the parens do not force sigil binding precedence. In this case, they create a list with one element - $ar_ref. If you then try to use the $# sigil on that list, you get a warning, because that sigil is only applicable for arrays (which are different from lists)

Here's some code to demonstrate.

http://gist.github.com/149089

Now, the different semantics of arrays and lists - *I* think that's weird, but every language has it's quirks like that (more or less!) :)

Dmitry Kan said...

Thanks for the valuable comment Hercynium.

I should perhaps mention, I enjoy coding Perl and that the posting title has been a play around Larry Wall's "If you think that Perl is weird, it actually is weird" (not a citation).

On the other hand this was the first time I ever needed as you call it "sigil" applied to an array reference and wanted to follow Larry's another saying "In general, if you think something isn't in Perl, try it out, because it usually is. :-) " (wiki-citation). To put it in easier words, I wanted just to go by intuition. The very first idea was to do a kind of unreferencing via smth like @($ar_ref) and then to try sigil on top of it. As one might guess it was equally awkward looking and not working.

However when I saw the proper way (without parentesis of course, it has been just an illustrative markup to support thinking behind), I felt a bit of a mystery:
a sharp sign surrounded with $ signs.

Those uninitiated beginners or random passer-by's may become too scared to continue learning Perl's syntax once they get to see such features. However I should say, Perl helps your brain keep working and has a lot of exciting moments.

Wraps Recipes said...

Interesting read, thanks for sharing