I've built a two dimension array with string values. There are always 12 columns but the number of rows vary. Now I'd like to build a string of each row but when I run the following code:
$outstring = "";
for ($i=0; $i < $ctrLASTROW + 1; $i++) {
for ($k=0; $k < 12; $k++){
$datastring = $DATATABLE[$i][$k]);
$outstring .= $datastring;
}
}
$outstring
takes the first value. Then on the second inner loop and subsequent loops the value in $outstring
gets overlaid. For example the first value is "DATE"
then the next time when the value "ABC"
gets fed to it. Rather than being the hoped for "DATEABC"
it's "ABCE"
. The "E"
is the fourth character of DATE
. I figure I'm missing the scalar / list issue but I've tried who knows how many variations to no avail. When I first started I tried the concatenation directly from the @DATATABLE
. Same problem. Only quicker.
When you have a problem such as two strings DATE
and ABC
being concatenated, and the end result is ABCE
, or one of the strings overwriting the other, a likely scenario is that you have a file from another OS, with the line endings \r\n
, which are chomp
ed, resulting in the string DATE\rABC
when concatenated, which then becomes ABCE
when printed.
In other words:
my $foo = "DATE\r\n";
my $bar = "ABC\r\n"; # \r\n line endings from file
chomp($foo, $bar); # removes \n but leaves \r
print $foo . $bar; # prints ABCE
To confirm, use
use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper $DATATABLE[$i][$k]; # prints $VAR1 = "DATE\rABC\r";
To resolve, instead of chomp
use a regex such as:
$foo =~ s/[\r\n]+\z//;