code_junkie

How can I read a custom defined pattern from a file in Perl?

Nov 13th, 2011
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. $cat error_log
  2.  
  3. <parameter>:test_tot_count
  4. <result>:1
  5. <stderr>:Expected "test_tot_count=2" and the actual value is 3
  6. test_tot_count = 3
  7. <parameter>:test_one_count
  8. <result>:0
  9. <stderr>:Expected "test_one_count=2" and the actual value is 0
  10. test_one_count = 0
  11. <parameter>:test_two_count
  12. <result>:4
  13. <stderr>:Expected "test_two_count=2" and the actual value is 4
  14. test_two_count = 4
  15. ...
  16.  
  17. my $err_msg = "";
  18. while (<ERR_LOG>)
  19. {
  20. if (/<parameter>:/)
  21. {
  22. s/<parameter>://;
  23. push @parameter, $_;
  24. }
  25. elsif (/<result>:/)
  26. {
  27. s/<result>://;
  28. push @result, $_;
  29. }
  30. elsif (/<stderr>:/)
  31. {
  32. if (length($err_msg) > 0)
  33. {
  34. push @stderr, $err_msg;
  35. }
  36. s/<stderr>://;
  37. $err_msg = $_;
  38. }
  39. else
  40. {
  41. $err_msg .= $_;
  42. }
  43. }
  44. if (length($err_msg) > 0)
  45. {
  46. push @stderr, $err_msg;
  47. }
  48.  
  49. use 5.010;
  50.  
  51. while (<ERR_LOG>) {
  52. chomp;
  53. given ($_) {
  54. when ( m{^<parameter>: (.*)}x ) { push @parameter, $1 }
  55. when ( m{^<result>: (.*)}x ) { push @result, $1 }
  56. when ( m{^<stderr>: (.*)}x ) { push @stderr, $1 }
  57. default { $stderr[-1] .= "n$_" }
  58. }
  59. }
  60.  
  61. use 5.010;
  62.  
  63. my @records;
  64.  
  65. my $prev_key;
  66.  
  67. while (<ERR_LOG>) {
  68. chomp;
  69. given ($_) {
  70. when ( m{^<parameter> }x ) { push(@records, {}); continue; }
  71. when ( m{^<(w+)>: (.*)}x ) { $records[-1]{$1} = $2; $prev_key = $1; }
  72. default { $records[-1]{$prev_key} .= "n$_"; }
  73. }
  74. }
  75.  
  76. (
  77. {
  78. parameter => 'test_one_count',
  79. result => 0,
  80. stderr => qq{Expected "test_one_count=2" and the actual value is 0ntest_one_count=0},
  81. },
  82. {
  83. parameter => 'test_two_count',
  84. result => 4,
  85. stderr => qq{Expected "test_two_count=2" and the actual value is 4ntest_two_count=4},
  86. }
  87. )
  88.  
  89. my( $err_msg , %data );
  90.  
  91. while (<ERR_LOG>) {
  92. if(( my $key ) = $_ =~ s/^<(parameter|result|stderr)>:// ) {
  93. if( $key eq 'stderr' ) {
  94. push @{ $data{$key} } , $err_msg if $err_msg;
  95. $err_msg = $_;
  96. }
  97. else { push @{ $data{$key} } , $_ }
  98. }
  99. else { $err_msg .= $_ }
  100. }
  101.  
  102. # grab the last err_msg out of the hopper
  103. push @{ $data{stderr} } , $err_msg;
  104.  
  105. if (/^<parameter>:/)
  106.  
  107. if (/^<parameter>:(.*)/s)
  108. {
  109. push @parameter, $1;
  110. }
Add Comment
Please, Sign In to add comment