Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

reduce line of code

by Sun751 (Beadle)
on Jul 14, 2009 at 05:58 UTC ( [id://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;

    CountZero

    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 (Archbishop) 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 (Patriarch) 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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://779799]
Approved by ysth
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-03-28 16:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found