Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The problem is in practice @_ is abused like crazy. For example:

1) I've often seen people shift from @_ half way in the middle of a function. If you really want to be certain about a method's formal parameters you have to read the entire function.

2) Also @_ is used in other circumstances which can cause mass confusion. For example Try::Tiny uses @_. It is difficult to guess if you getting a formal parameter or something else entirely (I"m not a fan of magic variables in case you can't tell). If you're Chromatic you might be able to know the probably hundred of uses of @_, but for a normal programmer you're screwed.

3) What if you want to use named parameters? You essentially have make a pointer to a hash, populate it, and unreference it. my $p = {'name' => 'val1', 'name2' => 'val2' }; f($p); sub f { my $name = $_[0]->{'name'}; my $name2 = $_[1]->{'name2'}; }

In other languages like python you can just do something like: def f(name, name2): ...

f(name = 'val', name2 = 'val2')

I've never seen a language handle function parameters as poorly as Perl. I forget almost all the Ruby I once knew but I'm pretty sure it is handled in a reasonable way similar to Python.



1) Adopt a convention of extracting your arguments at the beginning of the function.

Also, sometimes you just want to work on an arbitrary list of items. If you process one item and then shift it, that's a reasonable thing to do.

2. If you adopted the convention in 1, this shouldn't bite you. (I've never actually encountered this issue myself...)

3. You are misinformed. You can easily do something along the lines of:

    f({a => 'foo', b => 'bar'});
    
    sub f{ my ($args) = @_; say $args->{a}; }
There's probably a module of CPAN to do this even nicer.


Agreed. There is plenty of awful perl code out there. I have worked on codebases that did things like:

some_func(\%$some_object, \%some_hash);

and used variables like $a and $b as mainline code parameters...

However, if having dangerous features were something to hold against a language in general, nobody would be using C (maybe Linux in such an alternate universe would be written in Fortran or some other abomination). On the whole, I think that well-written Perl is very good. Poorly written Perl is... well, poorly written.


Thanks for the code sample and I like your convention. However, I can't enforce it on other people (especially at work) so it doesn't help me most of the time.


As for named parameters, the clean/simple style I like to use is:

do_stuff(Foo => 1, Bar => $baz);

sub do_stuff {

    my %args = @_;

    my $foo = $args{Foo};
    # etc...
}




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: