Frage

I have a subroutine in Perl that will read a hash and print out all of the key value pairs within the hash. However, instead of going through the foreach loop and printing each time it has a key, I need the result to be added to one scalar, and then return the scalar with the combined results at the end.

In Java I recall you could easily add additional text to a variable, but I'm not sure how to do this in Perl.

Any thoughts? I'll add my print code below, but I basically want to take that and add it to a scalar and return the combined scalar at the end (let's say $output)

sub printSongs
{
    print "Song Database\n\n";
    foreach $key (keys %songList)
    {
       print "Song Title: $key ---- Duration: $songList{$key}\n";
    }
}

PS: I tried to search for this answer as it should be relatively simple, but couldn't find anything. Not sure if append is the best word.

War es hilfreich?

Lösung

The concatenation operator in Perl is .. You can also combine it with an assignment as .=.

Andere Tipps

sub printSongs
{
    print "Song Database\n\n";

    foreach $key (keys %songList)
      {

       $something_combined = $something_combined . 
           "Song Title: $key ---- Duration: $songList{$key}\n";
      }

   print $something_combined;  

 }

You can easily append anything to a variable with a full stop character.

For example: $something = "Something" . $somevar . "Something else" . "etc";

In Java you normally use + to join strings. In Perl you can use .

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top