13

In my experience of languages that support the feature, programs that call functions with named parameters rather than positional parameters are easier to read and maintain.

I think Perl has this feature, but it's not working for me.

Is it a quirk of the package I'm using, or am I doing it wrong?

Setting up the function call

My fist Perl project is to use the HTML::TableExtract package to extract table data from HTML markup and display it as text.

The following code sets up the parser:

use strict;
use warnings;
use HTML::TableExtract;

my $markup = <<MARKUP;
<table>
  <tr> <th>a</th> <th>b</th> <th>c</th> </tr>
  <tr> <td>1</td> <td>2</td> <td>3</td> </tr>
  <tr> <td>4</td> <td>5</td> <td>6</td> </tr>
</table>
MARKUP

my $parser = HTML::TableExtract->new() ;

$parser->parse($markup) ;

The documentation says that I can dump output to the Command Prompt using the tables_dump method and use parameters $show_content and $col_sep to control the output format:

tables_report([$show_content, $col_sep])

Return a string summarizing extracted tables, along with their depth and count. Optionally takes a $show_content flag which will dump the extracted contents of each table as well with columns separated by $col_sep. Default $col_sep is ':'.

tables_dump([$show_content, $col_sep])

Same as tables_report() except dump the information to STDOUT.

Calling with positional and with named parameters

If I pass positional parameters in documentation order, I get the output I expect:

$parser->tables_dump(1, '_') ;

The columns are separated by an underscore instead of the default colon:

TABLE(0, 0):
a_b_c
1_2_3
4_5_6

Following Perl.com's Advance Subroutines article, I tried to pass a hash containing parameter names and values to clarify the meaning of the parameters:

$parser->tables_dump({show_content => 1, col_sep => '_'}) ;

Perl doesn't understand this. It ignores the value of col_sep and outputs with the default value:

TABLE(0, 0):
a:b:c
1:2:3
4:5:6

I get the same output if I don't try to change the separator:

$parser->tables_dump({show_content => 1}) ;

Even if I specify nonsense parameter names, I get the same output:

$parser->tables_dump({tweedledum => 1, tweedledee => '_'}) ;

Can I call this function using the named parameter style, or should I just settle for positional?

7 Answers 7

11

Perl doesn't natively support named parameters, however it's possible to design functions to accept named parameters (as a hash or hashref). It's up to the author of the function as to how they implement it. You'll need to supply arguments the function is expecting or you'll get unexpected results.

0
9

Named parameter passing in Perl (even with default values) is explained very well in Object Oriented Perl, Chapter 6. This style is very important and is widely used in object constructors. That's why it is explained in their OO Perl book.

I will quote two of their examples:

# This is how you call a subroutine using named argument passing
interests(name => "Paul", language => "Perl", favourite_show => "Buffy");

# This is how you define the subroutine to accept named arguments
sub interests {
   my (%args) = @_;

   # This is how you capture named arguments and define
   # defaults for the ones missing from a particular call.
   my $name           = $args{name}           || "Bob the Builder";
   my $language       = $args{language}       || "none that we know";
   my $favourite_show = $args{favourite_show} || "the ABC News";

   print "${name}’s primary language is $language. " .
   "$name spends their free time watching $favourite_show\n";
}

Another example that gives a different way of defining defaults (in a hash) is this:

my %defaults = ( pager => "/usr/bin/less", editor => "/usr/bin/vim" );

sub set_editing_tools {
    my (%args) = @_;

    # Here we join our arguments with our defaults. Since when
    # building a hash it’s only the last occurrence of a key that
    # matters, our arguments will override our defaults.
    %args = (%defaults, %args);

    # print out the pager:
    print "The new text pager is: $args{pager}\n";

    # print out the editor:
    print "The new text editor is: $args{editor}\n";
}
1
  • 1
    I wasn't looking for a way to create a module that accepts named parameters; I thought the HTML::TableExtract module already did accept named parameters. The question was based on a false premise. However, the Object Oriented Perl document will be very useful when I come to write my own Perl modules. Thanks for sharing. Aug 13, 2013 at 10:16
4

Following Perl.com's Advance Subroutines article, I tried to pass a hash containing parameter names and values to clarify the meaning of the parameters:

That article covers a way to write subroutines such that they will accept a hashref of named parameters. If you're calling a sub that isn't written to accept that, then it won't know how to handle it correctly.

$parser->tables_dump({show_content => 1, col_sep => '_'}) ;

Perl doesn't understand this. It ignores the value of col_sep and outputs with the default value:

Not to be overly pedantic, but Perl understands that just fine. However, tables_dump is only written to accept a list of scalar parameters. When you call it that way, it receives a single scalar parameter. This parameter just happens to be a reference to a hash, but tables_dump doesn't know or care about that, so it uses the reference as the value of $show_content. This is probably equivalent to passing 1 for show_content, since both 1 and any possible reference will evaluate as "true" in boolean context and I assume that $show_content is only ever used as a boolean.

Since there is no second parameter, nothing gets assigned to $col_sep, so it uses the default separator, as you observed.

1
  • 1
    Thanks for explaining the observed behavior. You are right, but Perl's understanding is not what I meant! Ultimately, it is I who does not understand Perl. Nov 26, 2012 at 21:16
4

Perl has no built-in support for named parameters. If you want to use them, the function has to be specifically written to accept arguments in that style. So you'll have to settle for positional arguments (or write a wrapper function (probably in a subclass)).

0
3

It's not too complicated. You pass the key-value pair like a hash or as a hash reference, and in the subroutine you load the arguments into a hash or hash reference.

# called like $parser->tables_dump({show_content => 1, col_sep => '_'}) ;
sub TheParser::tables_dump {
    my ($self, $args) = @_;
    if ($args->{show_content} == 1) {
        print join $args->{col_sep}, $self->the_column_data();
        ...
    }
}

With another line, you can load the named arguments you know about into appropriately named variables:

    my ($self, $args) = @_;
    my ($show_content, $col_sep) = @$args{qw(show_content col_sep)};
    if ($show_content == 1) {
       ...
3
  • Sorry, I don't understand. Are you showing me how to wrap the module method with one that accepts named parameters? Nov 26, 2012 at 21:14
  • No, this is how to write a new method that expects named parameters. Sorry if that's not quite what you asked for.
    – mob
    Nov 26, 2012 at 21:21
  • 1
    I'm not the maintainer of the module. I'm happy to accept whatever limitations it has. I have a lot to learn about Perl before I'd even consider submitting a patch for someone else's code. Nonetheless, thanks for trying to help! Your snippets give me some learning pointers. Nov 26, 2012 at 21:31
2

Going off just the title's question, you could do something like the below:

use strict;
use Carp::Assert;

sub func {
   my (%hash) = @_;
   assert($hash{'baz'} == 1);
   assert($hash{'mu'} == 2);
}

func('baz' => 1, 'mu' => 2);
-1

Here is a simple program I wrote that can use a type of named parameters. It allows for default values.

#!/usr/bin/perl
use strict;
use warnings;
use 5.014;
use POSIX qw/ strftime /;

# Script to get prior Monday (if today is Mon, then Mon a week ago).

for my $day (qw/ Sun Mon Tue Wed Thu Fri Sat /) {
    say "Last $day: ", last_monday( day => $day );  
}

sub last_monday {
    my %arg =  ( time => [localtime],
                 day  => 'mon',
                 span => 1,
                 @_
               );
    my $dow; # day of week

    if    ('sunday'    =~ /$arg{day}/i) { $dow = 0}
    elsif ('monday'    =~ /$arg{day}/i) { $dow = 1}
    elsif ('tuesday'   =~ /$arg{day}/i) { $dow = 2}
    elsif ('wednesday' =~ /$arg{day}/i) { $dow = 3}
    elsif ('thursday'  =~ /$arg{day}/i) { $dow = 4}
    elsif ('friday'    =~ /$arg{day}/i) { $dow = 5}
    elsif ('saturday'  =~ /$arg{day}/i) { $dow = 6}
    else {
        warn "$arg{day} is not a valid day of week. $!";
        return;
    }

    my ($wday, @dmy) = @{ $arg{time} }[6, 3..5];

    # (will work across month, year boundries)
    $dmy[0] -= ($wday - $dow) % 7 || ($arg{span} ? 7 : 0); # $dmy[0] == mday
    return strftime "%Y%m%d", 0,0,0,@dmy;
}
2
  • Can you use more English in your answer? I don't understand Perl well enough to see how this answers my question at all. Nov 26, 2012 at 21:24
  • @isme Sorry for the poor answer isme. I didn't read your question carefully. If I could have deleted my post, I would have. Nov 27, 2012 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.