tart has asked for the wisdom of the Perl Monks concerning the following question:

Please suggest me to write this code in (better way)professional way,
my $val; $val = return1(); if ($val) { $val .= return2(); } else { $val = return2(); }
Cheers!!!

Replies are listed 'Best First'.
Re: append return if defined else not
by ikegami (Patriarch) on Jul 14, 2010 at 00:10 UTC

    In the interest of keep the code clear and short, my answer depends on what false values return1 could return. The subject seems to indicate you only want to check for undefined, so the second and third solution would be appropriate. (The first would work, but it would also issue a warning.)

    If the false values return1 can return are empty strings:

    my $val = return1() . return2();

    If the false values return1 can return are undef and/or empty strings:

    my $val = return1(); $val .= return2();

    If the false values return1 can return are undef and/or empty strings:

    my $val = (return1() // '') . return2(); # 5.10+

    If return1 can return zero, then you have a weird function.

Re: append return if defined else not (or)
by tye (Sage) on Jul 14, 2010 at 04:54 UTC

    My answer does not depend on what "false" values might be returned:

    my $val= return1() || ''; $val .= return2() || ''; # or my $val= join '', return1() || '', return2() || '';

    - tye        

Re: append return if defined else not
by jethro (Monsignor) on Jul 14, 2010 at 00:00 UTC

    I assume you test for definedness (as you mention it in the title) and not for 0 or ''. In that case:

    use perl 5.10; $val= return1() // '' . return2();

    It might be necessary to add parens if . binds stronger than //

Re: append return if defined else not
by AnomalousMonk (Archbishop) on Jul 14, 2010 at 22:24 UTC
    ... write this code in [a more] professional way ...

    Any consideration of 'professionalism' is likely to lead into realms of religious controversy, if not outright schism. I rush in.

    I have not checked the solutions given by others, but they seem reasonable in terms of logical correctness.

    However, except for the problem, already mentioned, that the code of the OP tests for truth rather than for defined-ness, which the node title suggests is the true concern of tart, I'm not sure I would change the code at all. It's a bit verbose, but it's clear enough to need no comment whatsoever.

    Is the code logically correct? Does the writer clearly understand it? Will the maintainer (who may be the writer six months or a year hence) clearly understand it? If the answers to these questions are all 'yes', professionalism would seem to militate against a more terse approach which, in this case, will probably need at least one line of comment by the writer and a quick consultation of perlop by the maintainer for a precedence refresher.