title: Perl: Encoding messed up after text concatenation
body: <p>I have encountered a weird situation while updating/upgrading some legacy code.</p>
  
  <p>I have a variable which contains HTML. Before I can output it, it has to be filled with lots of data. In essence, I have the following:</p>
  
  <pre><code>for my $line (@lines) {
      $output = loadstuff($line, $output); 
  }
  </code></pre>
  
  <p>Inside of <code>loadstuff()</code>, there is the following</p>
  
  <pre><code>sub loadstuff {
      my ($line, $output) = @_;
      # here the process is simplified for better understanding.
      my $stuff = getOtherStuff($line);
      my $result = $output.$stuff;
      return $result;
  }
  </code></pre>
  
  <p>This function builds a page which consists of different areas. All area is loaded up independently, that's why there is a for-loop.</p>
  
  <p>Trouble starts right about here. When I load the page from ground up (click on a link, Perl executes and delivers HTML), everything is loaded fine. Whenever I load a second page via AJAX for comparison, that HTML has broken encoding.</p>
  
  <p>I tracked down the problem to this line <code>my $result = $output.$stuff</code>. Before the concatenation, <code>$output</code> and <code>$stuff</code> are fine. But afterward, the encoding in <code>$result</code> is messed up.</p>
  
  <p>Does somebody have a clue why concatenation messes up my encoding? While we are on the subject, why does it only happen when the call is done via AJAX?</p>
  
  <h3>Edit 1</h3>
  
  <p>The Perl and the AJAX call both execute the very same functions for building up a page. So, whenever I fix it for AJAX, it is broken for freshly reloaded pages. It really seems to happen only if AJAX starts the call.</p>
  
  <p>The only difference in this particular case is that the current values for the page are compared with an older one (it is a backup/restore function). From here, everything is the same. The encoding in the variables (as far as I can tell) are ok. I even tried the Encode functions only on the values loaded from AJAX, but to no avail. The files themselves seem to be utf8 according to "Kate".</p>
  
  <p>Besides that, I have a another function with the same behavior which uses the EXACT same functions, values and files. When the call is started from Perl/Apache, the encoding is ok. Via AJAX, again, it is messed up.</p>
  
  <p>I have been examinating the AJAX Request (jQuery) and could not find anything odd. The encoding seems to be utf8 too.</p>