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?
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.
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?
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.