See below the quoted text
On 02/03/2014 08:12 PM, SSC_perl wrote:
I'm having a problem with the script below. I want to alter just the first line
of a CSV file, removing the prefix "tag_" from each value in that line.
However, because the new line is shorter than the original, the script is only
over-writing part of the original line (exactly the number of characters of the new
line).
Is there a way to replace the entire line with the new, shorter one?
Thanks,
Frank
use strict;
use warnings;
my $filename = 'products.csv';
open (my $fh, '+<', $filename) || die "can't open $filename: $!";
my $line = <$fh>;
$line =~ s/tag_//gi;
seek $fh, 0, 0;
printf {$fh} $line;
close $fh;
http://www.surfshopcart.com/
Setting up shop has never been easier!
I am sorry to be a Johnny-come-lately here with a suggestion, but here goes.
If I needed to do this, I would probably use something like:
#!/usr/bin/perl -pi
s/tag_//g if $. == 1;
Not as fancy as the other suggestions, but it does work.
If I saved this as 'fixlabels.pl', for example, then I would invoke it as:
fixlabels.pl <file_to_fix>
If, for some reason, I wished to preserve the original file, then I
would use:
#!/usr/bin/perl -pi.bak
s/tag_//g if $. == 1;
This would leave a copy of the original file, with an extension of
'.bak' appended to the name
Finally, I might not even script this, since it is technically a one-liner..
perl -p -i.bak -e 's/tag_//g if $. == 1' <file_to_fix>
Have fun
Nathan
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/