Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

reduce line of code

by Sun751 (Beadle)
on Jul 14, 2009 at 05:58 UTC ( #779799=perlquestion: print w/replies, xml ) Need Help??
Sun751 has asked for the wisdom of the Perl Monks concerning the following question:

is there any shorter way to do below task???
if ($step_no) { my $cmd = $step_no; } else { my $cmd = 0; }
Any suggestion please???

Replies are listed 'Best First'.
Re: reduce line of code
by CountZero (Bishop) on Jul 14, 2009 at 06:30 UTC
    my $cmd = $step_no ? $step_no : 0;


    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: reduce line of code
by Your Mother (Bishop) on Jul 14, 2009 at 06:16 UTC

    This is probably what you're after.

    my $cmd = $step_no || 0; # If $step_no is 0, it assigns... uh, 0 over it.

    Note that if you're accepting user input, like $step_no = param("step") or something you should validate all user parameters before using them in other code. Perhaps-

    my $cmd = $step_no =~ /\A\d+\z/ ? $step_no : 0;
        I guess this is what Sun751 meant. His non-working example scopes the $cmd variable to the if ... else blocks.
Re: reduce line of code
by JavaFan (Canon) on Jul 14, 2009 at 09:40 UTC
    Yes, you can replace it with the empty statement. All you are doing in each block is setting a variable which is lexical to the block - and will hence be gone on block exit.

    Effectively, the above statement does nothing at all (unless there's some magic attached to $step_no).

Re: reduce line of code
by ikegami (Pope) on Jul 14, 2009 at 15:05 UTC
    Already mentioned:
    my $cmd = $step_no ? $step_no : 0;
    Simplifies to:
    my $cmd = $step_no || 0;
    If $step_no is only false when $step_no is zero, then it can even be simplified to
    my $cmd = $step_no;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://779799]
Approved by ysth
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2018-05-25 22:46 GMT
Find Nodes?
    Voting Booth?