Nathan Stanford II
Nathan Stanford II

Reputation: 617

Perl append prefix looping array

I am working on appending a file extension while looping over an array. The expected output is ABC001.csv for example but the output looks more like .csv01.

Any help on how to do this is greatly appreciated. I can provide more code if necessary.

foreach my $name (@source){
print "${name}.csv\n";
} 

Upvotes: 1

Views: 1702

Answers (2)

TLP
TLP

Reputation: 67900

user5402's answer is correct. I just wanted to share some perl features:

s/\s*$/.csv/, say for @source;

Or split up, to avoid possible conflicts:

s/\s*$/.csv/ for @source;
say for @source;

say is enabled with use v5.10 or use feature qw(say), and is simply print with a newline appended to the end.

The substitution will replace any whitespace -- including carriage returns -- at the end of your strings with ".csv". If there is no whitespace, it will just add ".csv", since the quantifier * allows for zero matches, and the anchor $ matches the end of the string.

One bit of magic is that $_ is aliased in the subscript loop to all the elements of @source, and therefore is permanently changed by the substitution.

Upvotes: 1

ErikR
ErikR

Reputation: 52029

I am certain that you have carriage returns at the end of your file names. That is, $name is being set to "ABC001\r". When you print "$name.csv\n", you are getting:

ABC001<-
.csv

which looks like .csv01 on your screen.

A quick fix would be to remove the carriage return like this:

for my $name (@source) {
  $name =~ s/\r//g;
  print "$name.csv\n";
}

but a better solution would be to remove the carriage returns at the point where the data comes into your application.

Upvotes: 6

Related Questions