Sunday, May 12, 2013

If I Could Change Perl

Is there something that irritates you about Perl? One little thing you wish you could change, to make life so much easier?

For me, it's the way declarations work. Whether it's with local, our or my, you can declare a variable name, or a list of several variable names:

my ($x, $y, $z);
Of course, you can initaliaze variables as you declare them.
my $bank_balance = -999_999;
my ( $x, $y, $z ) = ( 0, 0, 0 );

But if you have a number of variables to declare, and they aren't directly related to each other, as (x, y, z) clearly are, it would be so much better to declare the variable and immediately assign a value to it on the same line, the way C, Javascript and numerous sensible langages do.

Currently, 'my', 'our' and 'local' expect a variable name, or a list of mariable names. So one possibility would be to provide an alternative form which takes a hash. Ideally, values defined in one line could be used lower down.

my {
    $sides => 3,
    $lengths => [3, 4, 5],
I suppose people will ignore this article or come out with an explanation of why I'm wrong.
All the same, what little feature would make your Perl day better?


Caleb Cushing said...

exception objects, try/catch syntax, Carp functions become syntax, and the deprecation of die (must be an object or Carp function).

Tom Legrady said...

Would be nice to have them in the language, but they do exist as modules.

Caleb Cushing said...

try/catch as modules doesn't allow me to return in the try/catch which results in me writing code to compensate. Exception modules are all over the place and there's real telling what the good ones are (unless you know the authors). Die is just a bane on the debugging dev but some people don't want to put `use Carp` because it adds a dependency. Basically modules have taken us as far as we can go here... this really needs to be language features. Modules are great but they have limits.

pmakholm said...

If the variables are not related, then don't declare them in the same statement.

I do not see any advantage with your proposed syntax over just using multiple declarations of independent variables.

As I see it this is also how it is done in C.

abraxxa said...

This should work, although I see no benefit over declaring each var on its own line:

my ( $sides, $lengths ) = ( 3, [3, 4, 5] );