rodee
rodee

Reputation: 3161

Perl multiline pattern match using grep

Here is my script to check if copyright exists in a file.

use strict;
use warnings;
use List::Util 'first';

my $filename="sample.txt"; # this file name will be passed-in to the script.
my @fileContent=`cat $filename`;
my $copyrightFound = first { /copyright .* Shakespeare/i } @fileContent;
if (!$copyrightFound) {
   print "\nERROR: Copyright missing\n";
   exit;
}
#copyright Found
print @fileContent;
if (grep /Copyright (c) \d+ by Bill Shakespeare\nAll rights reserved./,@fileContent ) {
  print "\nCopyright is good\n";
} else {
  print "\nCopyright needs to be fixed\n";
}

prints:

$ perl copyrightCheck.pl 
Copyright (c) 2010 by Bill Shakespeare
All rights reserved.


Copyright needs to be fixed

but the copyright is good, is there a better way to check this? or whats wrong with my grep command? also All rights reserved. can appear in the same line or next line, can I use \n* to check the same?

Upvotes: 0

Views: 326

Answers (1)

bart
bart

Reputation: 898

The problem is that you loaded the file into an array of file's lines, so Copyright (c) 2010 by Bill Shakespeare and All rights reserved. end up in separate array elements. You then try to match your multi-line copyright string on the elements of this array, which fails.

To fix this, you can try loading the file into a scalar and use regex match on that scalar. You also need to escape any parentheses that you want to match:

my $fileContent = `cat $filename`;
...
if ($fileContent =~ /Copyright \(c\) \d+ by Bill Shakespeare\nAll rights reserved./)
{
    ...
}

I would also advice you to use Perl's open function and <> operator to load the contents of a file to a variable.

Upvotes: 1

Related Questions