search and replace last line character in perl

Sun microsystems Sun fire v20z amd opter...
January 23, 2012 at 12:15:14
Specs: CentOS
I have a very simple perl question. I thought I got it but for some reason it is not working. I have file that every line as a comma at the end. I would like to remove the last comma character at the end of the line. This is what what I have:

my @lines=split(/\n/, $content);

foreach my $line (@lines) {
$line=~s/,$//g;
print "$line\n";
}

this does not work, any ideas?


See More: search and replace last line character in perl

Report •

#1
January 23, 2012 at 13:24:09
How are you populating the $content variable?? This removes the last comma in each line for me which is essentially your program:

#!/usr/bin/perl -w

my $content = "line 1 with a comma,\nline 2 with a comma,\nline 3 with a comma,\n";

print $content;

my @lines=split(/\n/, $content);

foreach my $line (@lines) {
   $line=~s/,$//g;
   print "$line\n";
}


Report •

#2
January 23, 2012 at 13:29:30
$content is the comma separated file that is called with a web service call. It has comma separated data in it. I would like to remove the last comma in this file.

Report •

#3
January 23, 2012 at 15:30:36
OK, if the file looks like this:

my $content = "line 1 with a comma,\nline 2 with a comma,\nline 3 with a comma,\n";

I am interpreting that you only want to remove the last comma.

Then, this should do what you want if you want to remove the very last comma:

#!/usr/bin/perl -w

my $content = "line 1 with a comma,\nline 2 with a comma,\nline 3 with a comma,\n";

$content =~ s/,$//;
print $content;
# end script

your perl code using the foreach loop, removes the comma from each line.


Report •
Related Solutions


Ask Question