문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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 .

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top