Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re^3: Removing specific array elements

by poj (Abbot)
on Feb 01, 2016 at 14:29 UTC ( #1154185=note: print w/replies, xml ) Need Help??

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: <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


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


    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.


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


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


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1154185]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (2)
As of 2022-05-28 11:47 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (99 votes). Check out past polls.