http://qs321.pair.com?node_id=1154185


in reply to Re^2: Removing specific array elements
in thread Removing specific array elements

If I have read correctly you are scanning an input file and outputting changed lines only where column 12 is 000015, 000030 or 000060. Column 13 is changed to 92, 46 or 23 and a number of blank columns (8, 4 or 2) starting at 30 are removed.

Since there looks to be a pattern to your changes I have coded them into a hash to avoid the multiple ifs.

#!/usr/bin/perl use strict; use warnings; my $infile = $ARGV[0]; my $outfile = $ARGV[1] || 'resultfile.txt'; unless (@ARGV) { die "Usage: ReplaceNewLine.pl <inputfile> [<outputfile>] \n"; } open IN, '<', $infile or die "$infile not found in current location"; open OUT, '>', $outfile or die "Cannot open $outfile"; # Place header from source file into $header variable my $header = <IN>; print OUT $header; # changes my %change = ( '000015' => [92,30,8], '000030' => [46,30,4], '000060' => [23,30,2], ); # enhanced or standard files my @field = split "~",<IN>;; my $filetype = $field[14] ? 'Enhanced' : 'Standard'; if ($filetype eq 'Enhanced') { # process lines my $count=0; foreach my $line (<IN>) { ++$count; chomp($line); my @field = split "~", $line; if ( exists $change{$field[11]} ) { $field[12] = $change{$field[11]}[0]; my $posn = $change{$field[11]}[1]; my $cut = $change{$field[11]}[2]; my $discard = join '',splice(@field,$posn,$cut); warn "Warn : $discard discarded at line $count" if ($discard); print OUT join '~',@field; print OUT "\n"; } } print "$count lines processed from $infile\n"; } close IN; close OUT;

Note the first 2 lines of input are not processed

poj

Replies are listed 'Best First'.
Re^4: Removing specific array elements
by phamalda (Novice) on Feb 02, 2016 at 23:05 UTC

    poj:

    It took me a minute to see how the use of the array inside the hash actually worked but this is brilliant! Thank you again for your assist on this. This is precisely where I needed to be.

    Pham

Re^4: Removing specific array elements
by phamalda (Novice) on Feb 01, 2016 at 14:48 UTC

    poj:

    This is perfect. I hadn't investigating using a hash in this code. Thank you so much.

    Pham