ewok ewok - 3 months ago 9
Perl Question

perl: append variable to string if it exists

What I want to do is create a string that, in the middle, has a certain string if a variable evaluates to true, but omits that section if it doesn't. So I'm trying to do this:

my $var1 = "hello";
my $var2 = shift;
my $var3 = "my friend";

if ($var2){
print "$var1 <$var2> $var3\n";
} else {
print "$var1 $var3\n";


$ perl test.pl
hello my friend
$ perl test.pl there
hello <there> my friend

That is obviously perfectly functional, but I'm wondering if there's a way to do the check inline. Something like:

print "$var1 " . ("<$var2> " if $var2) . "$var3\n";

But that gives me a syntax error. Or If there's a way to do it using substitution within the string, that would be even better.


To shift a variable from @_ and insert it, if it's there

print $var1 . (shift // '') . $var3;

For example

sub concat {
   my ($var1, $var2) = ("Hello", "Friend");
   print $var1 . (shift // '') . $var3, "\n";

concat(" my dear ");

There may be questions of design with spaces, please add as suitable. Prints

Hello my dear Friend

If the angle brackets need be inserted around the variable, with $var2 already declared

print "$var1 " . (defined $var2 ? "<$var2>" : '') . "$var3\n";

You can also form the original string and then use substr conditionally but that seems to be more cumbersome.