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?

that is a unix problem and can't be done in any language. files can't be shortened from the beginning. you have to move all the later data down to fill in any gap you make. the normal solution is to write out to a new file with the shorter line and then the rest of the original file. then you can rename it to the original.

but File::Slurp has edit_file and edit_file_lines which do that for you. you can also try Tie::File.

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;

is the first line the only one with tag_? do you have multiple replacements on that line? if there is only one tag_ on the first line then this will work:

        use File::Slurp qw( edit_file ) ;

        edit_file { s/tag_// } 'products.csv';

if you have tag_ more than once on that line you may need edit_file_lines and a way to only modify the first line. a boolean could do that.

        use File::Slurp qw( edit_file_lines ) ;
        my $tag_done ;
        edit_file_lines { s/tag_//g unless $tag_done++ } 'products.csv';

uri

--
Uri Guttman - The Perl Hunter
The Best Perl Jobs, The Best Perl Hackers
http://PerlHunter.com

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to