Below I have a list of data I am trying to manipulate. I want to split the columns and rejoin them in a different arrangement.
I would like to switch the last element of the array with the third one but I'm running into a problem. Since the last element of the array contains a line character at the end, when I switch it to be a thrid, it kicks everything a line down.
CODE
while (<>) {
my @flds = split /,/;
DO STUFF HERE;
ETC;
print join ",", @flds[ 0, 1, 3, 2 ]; # switches 3rd element with last
}
SAMPLE DATA
1,josh,Hello,Company_name
1,josh,Hello,Company_name
1,josh,Hello,Company_name
1,josh,Hello,Company_name
1,josh,Hello,Company_name
1,josh,Hello,Company_name
MY RESULTS - Kicked down a line.
1,josh,Company_name
,Hello1,josh,Company_name
,Hello1,josh,Company_name
,Hello1,josh,Company_name
,Hello1,josh,Company_name
,Hello1,josh,Company_name,Hello
*Desired REsults**
1,josh,Company_name,Hello
1,josh,Company_name,Hello
1,josh,Company_name,Hello
1,josh,Company_name,Hello
1,josh,Company_name,Hello
1,josh,Company_name,Hello
I know it has something to do with chomp but when I chomp the first or last element, all \n are removed. When I use chomp on anything in between, nothing happens. Can anyone help?
chomp
removes the trailing newline from the argument. Since none of your four fields should actually contain a newline, this is probably something you want to do for the purposes of data processing. You can remove the newline with chomp
before you even split the line into fields, and then add a newline after each record with your final print statement:
while (<>) {
chomp; # Automatically operates on $_
my @flds = split /,/;
DO STUFF HERE;
ETC;
print join(",", @flds[0,1,3,2]) . "\n"; # switches 3rd element with last
}