ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.10. Interpolating Functions and Expressions Within StringsProblemYou want a function call or expression to expand within a string. This lets you construct more complex templates than with simple scalar variable interpolation. SolutionYou can break up your expression into distinct concatenated pieces: $answer = $var1 . func() . $var2; # scalar only Or you can use the slightly sneaky $answer = "STRING @{[ LIST EXPR ]} MORE STRING"; $answer = "STRING ${\( SCALAR EXPR )} MORE STRING"; DiscussionThis code shows both techniques. The first line shows concatenation; the second shows the expansion trick: $phrase = "I have " . ($n + 1) . " guanacos."; $phrase = "I have ${\($n + 1)} guanacos."; The first technique builds the final string by concatenating smaller strings, avoiding interpolation but achieving the same end. Because print "I have ", $n + 1, " guanacos.\n"; When you absolutely must have interpolation, you need the punctuation-riddled interpolation from the Solution. Only You can do more than simply assign to a variable after interpolation. It's a general mechanism that can be used in any double-quoted string. For instance, this example will build a string with an interpolated expression and pass the result to a function: some_func("What you want is @{[ split /:/, $rec ]} items"); You can interpolate into a here document, as by: die "Couldn't send mail" unless send_mail(<<"EOTEXT", $target); To: $naughty From: Your Bank Cc: @{ get_manager_list($naughty) } Date: @{[ do { my $now = `date`; chomp $now; $now } ]} (today) Dear $naughty, Today, you bounced check number @{[ 500 + int rand(100) ]} to us. Your account is now closed. Sincerely, the management EOTEXT Expanding backquotes ( Although these techniques work, simply breaking your work up into several steps or storing everything in temporary variables is almost always clearer to the reader. In version 5.004 of Perl, See Alsoperlref (1) and the "Other Tricks You Can Do with Hard References" section of Chapter 4 of Programming Perl |