Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

It has been a while since I have done any perl. I simple want to search a line of text in a file, e.g. REG-NZL-PUB.1981-263 ##1981## 19810922 and, in finding the 4 digit number in hashes above see if it matches the four digit number directly to the right. If it does match then delete the line. In this case the line would be deleted because 1981 exists twice. Can anybody help.

Replies are listed 'Best First'.
Re: Search and replace
by Enlil (Parson) on Mar 19, 2003 at 01:31 UTC
    This should work with some modifications to better suit your purposes:
    while ( <DATA> ) { print unless m/##(\d+)## \1/; } __DATA__ REG-NZL-PUB.1981-263 ##1981## 19810922 REG-NZL-PUB.1981-263 ##1981## 19820922 REG-NZL-PUB.1981-263 ##1981## 19830922 REG-NZL-PUB.1981-263 ##1981## 19840922 REG-NZL-PUB.1981-263 ##1982## 19810922 REG-NZL-PUB.1981-263 ##1983## 19810922 REG-NZL-PUB.1981-263 ##1984## 19810922 REG-NZL-PUB.1981-263 ##1985## 19850922
    Resulting in:
    REG-NZL-PUB.1981-263 ##1981## 19820922 REG-NZL-PUB.1981-263 ##1981## 19830922 REG-NZL-PUB.1981-263 ##1981## 19840922 REG-NZL-PUB.1981-263 ##1982## 19810922 REG-NZL-PUB.1981-263 ##1983## 19810922 REG-NZL-PUB.1981-263 ##1984## 19810922

    Note that I am assuming that the patterns of the lines in question are all the same.

    -enlil

Re: Search and replace
by The Mad Hatter (Priest) on Mar 19, 2003 at 01:38 UTC
    This should do the trick (though I don't know how efficient it is):
    open OUT, ">filename" or die "can't open file for writing: $!"; while (<DATA>) { my ($one, $two) = m|##(\d{4,4})## *(\d{4,4})|; print OUT $_ unless $one == $two; } __DATA__ REG-NZL-PUB.1981-263 ##1981## 19810922
    You'll have to modify it to use your filehandle (instead of <DATA>) that you open to read from.