Pages: Welcome | Projects

Perl foo THING and things

2015/1/11
Tags: [ perl ]

Programming backport in some relaxed spare time gave me the opportunity to improve my Perl.

I started using Perl a bunch of years ago, just because I felt like it's good to learn it, although I already know Python. So, I was reading the perlref, trying to figure out something I never was able to get: the foo{THING} syntax.

To be honest, I found this part of the manual quite difficult to understand. In the first place I had some difficulty in getting the purpose of the * operator. It has to do with references, but it's also known as typeglob… what the hell is that for?

Many will agree on this point: the best way of getting it is trying. So I tarted with some silly test, just to see what's happening...

#!/usr/bin/perl -w

use strict;
use warnings;
use feature 'say';

my $foo = 3;
my @foo = (9, $foo, 4, 5);

my $x = *foo;
say "What is what? $$x @$x";

After reading the documentation, I expected to see the content of $foo and @foo. But the interpreter here complains:

Name "main::foo" used only once: possible typo at foo-thing.pl line ...
Use of uninitialized value in concatenation (.) or string at foo-thing.pl
line 17.
What is what?  

So I was about to give up, at this point… when I tried to assign *ARGV{ARRAY} to a scalar. And it worked. I created a reference to the array! At this point I realized that my was my problem. Quoting the perlref:

Variables declared with "my" are not part of any package and are therefore
never fully qualified with the package name. In particular, you're not
allowed to try to make a package variable (or other global) lexical:

    my $pack::var;      # ERROR!  Illegal syntax

So that's it. Let's retry without the my, and let's use package-level variables instead! Then let the context decide what we are using!

#!/usr/bin/perl -w

use strict;
use warnings;
use feature 'say';

$main::foo = 3;
@main::foo = (9, $main::foo, 4, 5);
sub foo { 55 };

my $x = *foo;

say "What is what? $$x @$x " . &$x;

Play a bit with this, master the foo{THING}, and possibly other things.