Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

anyway to combine these two steps?

by convenientstore (Pilgrim)
on Jan 19, 2010 at 06:02 UTC ( [id://818111]=perlquestion: print w/replies, xml ) Need Help??

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

Hello monks,

just a question, is there anyway for me to combine below 2 statement into 1?
thank you in advance!!
($num) = $num =~ m#20(\d)#; ($num) = sprintf("%02d",$num);

Replies are listed 'Best First'.
Re: anyway to combine these two steps?
by ikegami (Patriarch) on Jan 19, 2010 at 07:02 UTC

    You are assuming it always matches (or else you'd get a warning), so I'm going to rely on that same assumption.

    ($num) = $num =~ /2(0\d)/;

    Without the assumption:

    $num = $num =~ /2(0\d)/ ? $1 : undef;

    An alternate solution:

    (...) = map sprintf('%02d', $_), ...
Re: anyway to combine these two steps?
by moritz (Cardinal) on Jan 19, 2010 at 11:24 UTC
    $num =~ s/.*?20(\d).*/0$1/gs

    Since \d always matches one digit, the sprintf is not really needed.

Re: anyway to combine these two steps?
by Anonymous Monk on Jan 19, 2010 at 06:59 UTC
    sprintf("%02d", $num =~ /20(\d)/);

    Note that $num =~ /20(\d)/ returns in list context the matches, and an empty list when there are none. So if you need to check whether a match occured, you can't do that here. However, you can provide to sprintf a default value, since it only uses the values it needs, and if there's an extra one it's ignored:

    sprintf("%02d", ($num =~ /20(\d)/), 0);

    A general example: print sprintf("%s\n", (/(bar)/), 'default') for qw(foo bar)

      Another method, from the unnecessary ternary operator dept:

      $output = (/20(\d)/ ? sprintf("%02d", $1) : format_error("that isn't valid data!"));

Re: anyway to combine these two steps?
by ambrus (Abbot) on Jan 19, 2010 at 11:17 UTC

    Actually you want $num = sprintf("%02d", $num % 100); to avoid Y2K errors.

Re: anyway to combine these two steps?
by Anonymous Monk on Jan 19, 2010 at 06:44 UTC
    ($num) = $num =~ m#20(\d)#; ($num) = sprintf("%02d",$num);
      ; separates statements. Putting two statements onto the same line does not make them a single statement any more than writing this as
      ($num) = $num =~ m#20(\d)#; ($num) = sprintf( "%02d", $num );
      makes it 11 statements.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2024-04-18 14:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found