6

Similar to this question regarding Ruby, I'd like to conditionally pass parameters to a method. Currently, I have it configured as follows:

my $recs = $harvester->listAllRecords(
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',
    from => $from,
    until => $until,
);

What I'd like is to be able to conditionally pass the from and/or until parameters, depending on previous code. This is not syntactically correct, but something like this:

from => $from if ($from),
until => $until if ($until),

or this:

if ($from) {from => $from,}
if ($until) {until => $until,}

Is this possible, and if so, how would I go about doing it?

Community
  • 1
  • 1
ND Geek
  • 398
  • 6
  • 21
  • 1
    Is this what your are looking for? http://stackoverflow.com/questions/8124138/how-to-pass-optional-parameters-to-a-perl-function – squiguy Jan 17 '13 at 18:36

2 Answers2

12

You could use the ternary ?: operator with list operands:

my $recs = $harvester->listAllRecords(
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',

    $from ? (from => $from) : (),
    $until ? (until => $until) : (),
);

It may also be worth knowing about the "conditional list include" pseudo-operator, which in this case would work like

...
(from => $from) x !!$from,
(until => $until) x !!defined($until),
...

but the ternary operator expression is probably easier to read for most people.

Community
  • 1
  • 1
mob
  • 117,087
  • 18
  • 149
  • 283
  • That did it, thanks! A quick Google and some following reading turned up the "Logical Defined-Or" (`//`), which while only tangentially related to my original question, appears very useful. – ND Geek Jan 17 '13 at 18:47
6

The other option is to build a list (or hash) of args and then call the method:

my %args = (
    metadataPrefix => 'marc21',
    metadataHandler => 'MARC::File::SAX',
    set => 'pd',
);
$args{from} = $from if $from;
$args{until} = $until if $until;

my $recs = $harvester->listAllRecords(%args);
Ryan C. Thompson
  • 40,856
  • 28
  • 97
  • 159