1# ==== Purpose ====
2#
3# Grep for a pattern in a file in a portable manner.
4#
5# WARNING: Use include/assert_grep.inc instead, if at all possible.
6# That allows you to assert the property being tested in a much more
7# precise way.  It also does not depend on the result file, so your
8# test becomes more readable/maintainable. It also produces better
9# debug output if the test fails.
10#
11# ==== Usage ====
12#
13# --let $grep_pattern= PERL_REGEX
14# --let $grep_file= FILENAME
15# [--let $grep_output= print_each | print_count | boolean]
16#
17# Parameters:
18#
19#   $grep_pattern
20#     The pattern to search for. This can be a perl regex.
21#
22#   $grep_file
23#     The file to search in.
24#
25#   $grep_output
26#     The format of the output. Can be one of:
27#     - print_each: prints each line, and a count.
28#     - print_count: print just a count.
29#     - boolean: print only whether something was found or not.
30#     If this is not specified, print_each is used.
31
32#--let $include_filename= grep_pattern.inc
33#--source include/begin_include_file.inc
34
35
36if ($grep_output)
37{
38  --let _GP_GREP_OUTPUT= $grep_output
39}
40if (!$grep_output)
41{
42  --let _GP_GREP_OUTPUT= print_each
43}
44--let _GP_GREP_PATTERN= $grep_pattern
45--let _GP_GREP_FILE= $grep_file
46
47--perl
48  use strict;
49  my $file= $ENV{'_GP_GREP_FILE'} or die "grep_file is not set";
50  my $pattern= $ENV{'_GP_GREP_PATTERN'} or die "grep_pattern is not set";
51  open(FILE, "$file") or die("Unable to open $file: $!\n");
52  my $count = 0;
53  my $output = $ENV{'_GP_GREP_OUTPUT'};
54  if ($output eq 'print_each') {
55    print "Matching lines are:\n";
56  }
57  while (<FILE>) {
58    my $line = $_;
59    if ($line =~ /$pattern/) {
60      if ($output eq 'print_each') {
61        print $line;
62      }
63      $count++;
64      if ($output eq 'boolean') {
65        last;
66      }
67    }
68  }
69  if ($count == 0 && $output eq 'print_each') {
70    print "None\n";
71  }
72  if ($output eq 'boolean') {
73    print $count ? "Pattern found.\n" : "Pattern not found.\n";
74  }
75  else {
76    print "Occurrences of '$pattern' in the input file: $count\n";
77  }
78  close(FILE) or die "Error closing $file: $!";
79EOF
80
81
82#--source include/end_include_file.inc
83