open FH, "+<testing.txt"; $keyField = "PPD6"; @searchList = qw(PPD6 16-Dec-15 Base5 no Yes g_<<date>> No No "N4,Q2"); $fieldNumber = 3; $valueToSet = "Ravitej"; splice @searchList, $fieldNumber,1, $valueToSet; my @lines=<FH>; open(FILE,">foo.txt")|| die "can't open file for write\\n"; foreach $line (@lines) { if($line =~ /$keyField/) { print FILE $searchList; } else { print FILE $line; } }#end foreach close(FH); close(FILE);
**Inputs:
**
PPD5 31-Dec-15 Basel5 No No
PPD5 23-Dec-15 Bas_15 No No
PPD6 16-Dec-15 Bas3_15 No No
NPD5 16-Dec-15 Bas15 No No
NPD6 16-Dec-15 Bas15 No No
PARU 9-Jan-16 hjfhg15 No No
OUTPUT:
PPD5 31-Dec-15 Basel5 No No
PPD5 23-Dec-15 Bas_15 No No
PPD6 16-Dec-15 Bas3_15 Ravitej No
NPD6 16-Dec-15 Bas15 No No
PARU 9-Jan-16 hjfhg15 No No
My problem is after PPD6 one row is missing. can anyone please resolve the issue.
The basic rules of debugging a Perl program is to turn on strict
and warnings
. strict
forces you to declare all your variables to avoid typos, and so they're not global. warnings
will warn you of things which are probably mistakes.
After turning on warnings with -w
we see the problem immediately.
$ perl -w ~/tmp/test.plx
Possible attempt to separate words with commas at /Users/schwern/tmp/test.plx line 3.
Name "main::searchList" used only once: possible typo at /Users/schwern/tmp/test.plx line 11.
Use of uninitialized value $searchList in print at /Users/schwern/tmp/test.plx line 11, <FH> line 6
You print $searchList
but there is no such variable. If you had strict
on this would have been an error you'd have seen immediately.
I also have to mention that you're failing to check that "testing.txt" opened. This isn't causing your problem, but it is one of the most common mistakes in Perl so it's worth pointing out.
open FH, "+<testing.txt";
It's also unnecessary to use +<
here as you're only using it for reading. Finally, I'd recommend using lexical filehandles instead of global globs as they will automatically close when they go out of scope.
Later on you do check whether the other file opens, but don't include $!
which will tell you why it failed to open.
In general, just use autodie
. This will make (almost) every IO operation throw a well formatted error message if it fails. Much better than having to remember to write "or die ..." everywhere.
use autodie;
open my $fh, "<", "testing.txt";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.