Perl Variable value is representing another variable

前端 未结 2 1566
野性不改
野性不改 2021-01-25 17:37
my $var = \"Hello\";
my $Hello = \"Hi\";

my question is: how can I substitute the value of $Hello in $var? Here $var contains string \"Hello\" (there i

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-25 18:17

    If you are willing to fill a placeholder in a string with the value of a variable, you could use :

    my $Hello = "Hi";
    my $var = "$Hello world";
    # $var is now "Hi world"
    

    If you want to replace each occurence of some variable name, you can use :

    my $Hello = "Hi";
    my $greet = "Hello, my name is Jimbo, and I hate Helloween.";
    $greet =~ s/Hello/$Hello/g;
    # $greet is now "Hi, my name is Jimbo, and I hate Hiween.";
    

    Like proposed by DVK, eval could also partially do the trick :

    my $Hello = "Hi";
    my $greet = "\$Hello, my name is Jimbo, and I hate \$Helloween.";
    $greet = eval "\"$greet\"";
    # $greep is now "Hi, my name is Jimbo, and I hate ."
    

    Edit: Sorry for the briefness of my previous answer, I typed it on my phone in a waiting room...

提交回复
热议问题