in reply to Pass an optional parameter to a subroutine

This is exactly the kind of problem that the forthcoming "defined or" (//) operator is designed to deal with. If you're using the current development version of Perl (5.9) or when the next stable version (5.10) is released, you'll be able to write

my $db_write = shift // 1;

Instead of

my $db_write = shift; $db_write = 1 unless defined $db_write;

Actually, I think that currently I'd write your code like this

my $ref_mail = shift; my $db_write = @_ ? shift : 1;
--
<http://dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re^2: Pass an optional parameter to a subroutine
by ysth (Canon) on Sep 15, 2006 at 08:36 UTC
    If you're using the current development version of Perl (5.9) or when the next stable version (5.10) is released, you'll be able to write
    Or if you build a 5.8.x perl with the appropriate dor-* patch from http://perl.com/CPAN/authors/id/H/HM/HMBRAND/
Re^2: Pass an optional parameter to a subroutine
by Tanktalus (Canon) on Sep 15, 2006 at 15:54 UTC

    Actually, I'd write it like that last way even with the // operator. It's just a good habit to be in for cases where undef actually is a legitimate value. For example, in a standard get/set object method, knowing that nothing is passed in (read-only) is a very different case from undef being passed in (setting the value to undef). Of course, I can't see using the ternary operator in that precise situation, just that it's an easy way to see the difference between no parameter and undef as a parameter.

    Of course, there are times where I don't want undef as a valid value - but I want my use of // to be an explicit statement that undef isn't allowed rather than an unintentional default.

Re^2: Pass an optional parameter to a subroutine
by radiantmatrix (Parson) on Sep 15, 2006 at 17:47 UTC

    Actually, I think that currently I'd write your code like this
    my $ref_mail = shift; my $db_write = @_ ? shift : 1;

    That's icky, as it means more to change if there are ever more parameters than just these two. I'd suggest:

    my $ref_mail = shift; my $db_write = defined $_[0] ? shift : 1;
    <radiant.matrix>
    A collection of thoughts and links from the minds of geeks
    The Code that can be seen is not the true Code
    I haven't found a problem yet that can't be solved by a well-placed trebuchet

      Exactly! What if someone sent in something like this?

      foo(undef, 1, 2);
      Then the @_ version would shift off the undef, which is not what is wanted, I think.

      Being contemplative
      -v.

      "Perl. There is no substitute."