msh210 has asked for the wisdom of the Perl Monks concerning the following question:
Hi, Monks, I have a bunch of scalar variables to include in a string. In order to avoid a bunch of ugly concatenation dots, I include them all in a double-quoted string. So far, so good. But one of the variables is to be followed, within the string, by some (non-variable alphanumeric) text. Obviously, I can't just concatenate them within the double-quoted string. Two options I can think of are: - print "The maximum number of $type" . "events on $date occurred $maxtimes times; it was $max.\n";
- print "The maximum number of $type$\events on $date occurred $maxtimes times; it was $max.\n"; if $\ is undefined
But I don't much like either of those. The first is a bit ugly/inelegant to my mind: I prefer one long double-quoted string. The second is dependent on a variable that may change in a later revision of the script; plus, it's distasteful to me because there's nothing tying $\ to this string semantically. Is there a more elegant way of doing this? Or is my option 1 (or 2?) considered elegant enough?
print map chr($w+=$_),74,43,-2,1,-84,65,13,1,5,-12,-3,13,-82,48,21,13,-6,-76,78,-9,18,-21,7,-4,-57,-34#stackoverflow.com/q/10858682
Re: How to include a string immediately after a variable in a double-quoted string
by dave_the_m (Monsignor) on Nov 20, 2015 at 21:13 UTC
|
print "The maximum number of ${type}events on $date occurred $maxtimes times; it was $max.\n";
Dave. | [reply] [d/l] |
Re: How to include a string immediately after a variable in a double-quoted string
by jeffa (Bishop) on Nov 20, 2015 at 21:44 UTC
|
printf "The maximum number of %sevents on %s occurred %d times; it was
+ %d.\n",
$type,
$date,
$maxtimes,
$max,
;
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
| [reply] [d/l] |
|
I always forget about printf in Perl. In Python (3+), there's no interpolation, so I'd have to do print("Hello {}, how are you {}".format(name, today)).
No matter what you want to print with variables, you have to do it this way (at least for a normal print statement), including all the parens and cruft.
I've taken perl interpolation for granted me thinks ;)
| [reply] [d/l] [select] |
|
Thank you! print map chr($w+=$_),74,43,-2,1,-84,65,13,1,5,-12,-3,13,-82,48,21,13,-6,-76,78,-9,18,-21,7,-4,-57,-34#stackoverflow.com/q/10858682
| [reply] |
Re: How to include a string immediately after a variable in a double-quoted string
by stevieb (Canon) on Nov 20, 2015 at 21:14 UTC
|
perl -E '$x="hi "; say "${x}there"'
hi there
| [reply] [d/l] [select] |
Re: How to include a string immediately after a variable in a double-quoted string
by msh210 (Monk) on Nov 20, 2015 at 21:16 UTC
|
Thank you, dave_the_m, stevieb! print map chr($w+=$_),74,43,-2,1,-84,65,13,1,5,-12,-3,13,-82,48,21,13,-6,-76,78,-9,18,-21,7,-4,-57,-34#stackoverflow.com/q/10858682
| [reply] |
|
|