code_junkie

How do I load a file into a Perl hash?

Nov 11th, 2011
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. department=value1
  2. location=valueA
  3. location=valueB
  4. department=value2
  5.  
  6. use File::Slurp;
  7. use Data::Dumper;
  8. my %hash = map {
  9. s/#.*//;
  10. s/^s+//;
  11. s/s+$//;
  12. m/(.*?)s*=s*(.*)/;
  13. } read_file($file);
  14. print Dumper(%hash);
  15.  
  16. $VAR1 = {
  17. 'location' => 'valueB',
  18. 'department' => 'value2'
  19. };
  20.  
  21. $VAR1 = {
  22. 'location' => 'valueA,valueB',
  23. 'department' => 'value1,value2'
  24. };
  25.  
  26. my %hash;
  27. while (<FILE>)
  28. {
  29. chomp;
  30. my ($key, $val) = split /=/;
  31. $hash{$key} .= exists $hash{$key} ? ",$val" : $val;
  32. }
  33.  
  34. name: Wally Jones
  35. department: [foo, bar]
  36. location: [baz, biff]
  37.  
  38. use File::Slurp;
  39. use YAML::XS;
  40. use Data::Dumper;
  41.  
  42. print Dumper Load scalar read_file(shift);
  43.  
  44. $VAR1 = {
  45. 'department' => [
  46. 'foo',
  47. 'bar'
  48. ],
  49. 'location' => [
  50. 'baz',
  51. 'biff'
  52. ],
  53. 'name' => 'Wally Jones'
  54. };
Add Comment
Please, Sign In to add comment