Reputation: 227
I have an array23 which contains strings of a file each in one line . Some strings have a "," in the end without a white space . I want to remove commas in the end of strings if they are present . I have tried the following code but is not working
#!/usr/bin/perl
use strict;
use warnings;
open my $abcd , '>','perl_script_3_out_1.txt' or die $!;
foreach( @array23 )
{
if ((substr $_,0,-1) =~ ",")
{
s/","//g;
}
}
print $abcd "$_";
close($abcd);
Upvotes: 0
Views: 1144
Reputation: 6578
Your program will not print anything as it stands, because your print statement (which is outside of your loop) refers to the default variable $_
, which only exists in your loop.
You are also performing a regex on ","
- which is not what you want (,
at the end of each string).
You should always add use strict
and use warnings
to the beginning of every script to catch this sort of thing
I would use something like this:
This only removes ,
that occur at the end of each line.
use strict;
use warnings;
for my $element (@array){
$element =~ s/,$//g;
print "$element\n";
}
Upvotes: 3