code_junkie

What is the easiest or most effective way to convert month's abbreviation to a number in Perl? (ie “jan” to 1)

Nov 11th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. %mon2num = qw(
  2. jan 1 feb 2 mar 3 apr 4 may 5 jun 6
  3. jul 7 aug 8 sep 9 oct 10 nov 11 dec 12
  4. );
  5.  
  6. $mon2num{"jan"}
  7.  
  8. my %number_for = (
  9. jan => 1,
  10. feb => 2,
  11. #etc...
  12. );
  13. #...
  14. do_something_with($number_for{$month})
  15.  
  16. my %month; @month{qw/jan feb mar apr may jun
  17. jul aug sep oct nov dec/} = (1 .. 12);
  18.  
  19. my %month_num = do { my $i = 1; map {; $_ => $i++ } (
  20. qw( jan feb mar apr may jun jul aug sep oct nov dec )
  21. ) };
  22.  
  23. my %month_num;
  24. $month_num{ $_ } = 1 + keys %month_num for (
  25. qw( jan feb mar apr may jun jul aug sep oct nov dec )
  26. );
  27.  
  28. my %month_num = do {
  29. my @month = qw( jan feb mar apr may jun jul aug sep oct nov dec );
  30. zip2( 1 .. 1+$#month, @month );
  31. };
  32.  
  33. # create a lookup table of month abbreviations to month numbers
  34. my %month_abbr_to_number_lkup = (
  35. jan => 1,
  36. feb => 2,
  37. mar => 3,
  38. apr => 4,
  39. may => 5,
  40. jun => 6,
  41. jul => 7,
  42. aug => 8,
  43. sep => 9,
  44. oct => 10,
  45. nov => 11,
  46. dec => 12,
  47. );
  48.  
  49. # get the number for a month
  50. my $number = $month_abbr_to_number_lkup{$abbr}
  51. || die "Could not convert month abbreviation '$abbr' to a number.";
  52.  
  53. %mon_2_num = (jan => 1,
  54. feb => 2,
  55. ...);
  56.  
  57. $month_number = $mon_2_num{lc($month_name_abbrev)};
  58.  
  59. @month{qw(jan feb mar apr may jun jul aug sep oct nov dec)} = 1..12;
  60.  
  61. my @months = qw(Jan Feb Mar Apr May Jun
  62. Jul Aug Sep Oct Nov Dec);
  63. my %monthnum = map { $_ => $months[ $_ - 1 ] } 1..12;
Add Comment
Please, Sign In to add comment