1

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.

4

2 回答 2

6

Perl 中的连接运算符是.. 您也可以将其与作业组合为.=.

于 2013-10-14T21:23:19.897 回答
0
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;  

 }

您可以轻松地将任何内容附加到带有句号字符的变量中。

例如: $something = "Something" 。$somevar 。“别的东西”。“ETC”;

在 Java 中,您通常使用 + 来连接字符串。在 Perl 中,您可以使用 .

于 2013-10-17T19:47:55.990 回答