0

For this script, I am pulling a csv file that includes what needs to be found and what the replacement is. Those values, $pattern1 and $replacement1 are then inserted into a find & replace function. Ideally this will take the csv key file & do an inplace replacement of the raw data file.

use English;
use strict;
use warnings;

sub inplace_sanitize {
my ( $datafile, $pattern1, $replacement1 ) = @_;
local @ARGV = ( $datafile ),
  my $INPLACE_EDIT = '.back';
while ( <> ) {
s/\Q$pattern1/$replacement1/g;
#print;
}
}

sub main 
{
# Select Key for Find & Replace
my $filename = 'stmre_fr_key.csv';

open(INPUT, $filename) or die "Cannot open $filename";

# Read the header line.
my $line = <INPUT>;

# Read the lines one by one.
while($line = <INPUT>)
{
    chomp($line);

    #Split & Assign
    my ($replacement1, $pattern1) = split(',', $line);

    # Select Data File
    my $datafile = 'rawdata.csv';

    #Find & Replace Data File
    &inplace_sanitize( $datafile, $pattern1, $replacement1 );
}   
}
close(INPUT);
main();

So this is not working, as it doesn't perform the replacement. Without the inplace_sanitizecall it prints out the $replacement1 & $pattern1 correctly. The inplace_sanitize works by itself if you define $replacement1 = 'replace'; and $pattern1 = 'find';. But together there it doesn't work. Any ideas?

Samples:

$replacement1 = '7306e005';
$pattern1 = 'leighs_satcon011016001_00753b94';

stmre_fr_key.csv:

find,replace
leighs_satcon011016001_00753b94,7306e005
leighs_satcon011016001_00753b95,7306e006
.
.
.
4
  • Show some sample input and output. Is your mapping file really of the form replacement,pattern, with replacement on the left? Commented Mar 13, 2014 at 22:09
  • 's/\Q$pattern1\E/\Q$replacement1\E/g;' try that, the importance here is that also ending the \Q with an \E, and your doing it for both. I stole this from Eclipse complete-ant-cmd.pl script :) Commented Mar 13, 2014 at 22:29
  • Your use of my $INPLACE_EDIT looks fishy. should be local $INPLACE_EDIT Commented Mar 13, 2014 at 22:45
  • Thanks for the upgrade alexmac. Commented Mar 13, 2014 at 23:54

1 Answer 1

2

You're use of my $INPLACE_EDIT is your problem. You want to effect the global variable:

local $INPLACE_EDIT = '.back';

The same way you're treating @ARGV

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, although for some reason its deleting all the content in that and the .back file.
Uncomment your print statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.