hash - Convert keys into days in perl -


i have hash have keys in number seprated _ 49_168. want convert these keys hours .if keys greater 48 have convert whole key in hours 49_168 key became "from 3 7 days"

my hash

{  '49_168' => {                 'amt' => "100"              },  '169_720' => {                 'amt' => "100"               },  '2_48' => {             'amt' => "100"            },  '721_-' => {               'amt' => "100"             } } 

what trying "

@timearray = split (/-/,$time_keys);     if(@timearray[0] > 48){         $desc .= "from ".ceil(@timearray[0]/24);     }     if(@timearray[1] > 48){         $desc .= "to ".ceil(@timearray[1]/24)."days";     } 

in case of - have show blank value. how can please me

desired output

'49_168' = "3days 7 days"      '169_720' ="8 days 30 days" '2_48' ="" '721_-' = "31 days onwards" // incase after _ - put onwards 

after discussing in chat, came this. created unit test cover cases named in comments of question.

use strict; use warnings; use test::more 'no_plan'; %input = (     '49_168'  => "3 days 7 days",     '169_720' => "8 days 30 days",     '2_48'    => '',     '721_-'   => "31 days onwards",     '2_49'    => "from 2 hours 3 days", );  while ( ( $input, $desired_output ) = each %input ) {     convert_to_day_string($input), $desired_output,        qq{"$input" becomes "$desired_output"}; } 

then can build function convert_to_day_string follows.

use posix 'ceil';  sub convert_to_day_string {     ($period) = @_;      ( $from, $to ) = split /_/, $period;      $from_string;     if ( $from < 49 ) {          # in hours         $from_string = sprintf 'from %d hours', $from;     }     else {         # in days         $from_string = sprintf '%d days', ceil( $from / 24 );     }      $to_string;     if ( $to =~ m/-/ ) {          # indefinite         $to_string = ' onwards';     }     else {         # small, abort         return q{} if $to < 49;          # in days         $to_string = sprintf ' %d days', ceil( $to / 24 );     }      return $from_string . $to_string; } 

i chose verbose instead of making idiomatic because think legibility you.


my advice in case this:

  • always use strict , use warnings, spot mistakes
  • if there several kinds of output, write test. helps not writing code, coming later if need change it. see test::more more information on that.
  • in terms of stack overflow, include code , sample input/output in queston others can , don't have ask stuff.

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -