子程序使用传入的字符串声明新变量作为其名称

时间:2017-01-28 20:22:30

标签: perl

我想要做的是:将一个名字(只是一个字符串)传递给一个子程序,然后让子程序用名称传递一个新变量。

解释性示例1(简体):

$name = "MyVariable";
declareNewVariable($name); #This line should work exactly as "my $MyVariable;"

sub declareNewVariable {
    my $newVariableName = shift;
    #…: Here should be a line to declare the new variable named by the passed string,
       #which I'm looking for.
}

解释性示例2(更详细):

$text = 'hello';
convert_to_uppercase_new($text,"CustomName");
    #Doesn't use declaration syntax each time I use the subroutine.
print $text; #Prints: hello
print $CustomName; #Prints: HELLO

sub convert_to_uppercase_new {
    #Should convert text to upper case then store the result in a new variable

    my ($content, $newVariableName) = @_;
        #The subroutine takes in the string to be converted to upper case
        #and another string to be used as the new variable name.

    …$newVariableName… = uc $content; 
        #dots (placeholder) represent blank space that should be filled with some
        #syntax that helps to declare the new variable with the name (string)
        #stored in $newVariableName.
}

只需使子程序返回一个值即可实现同样的目的:

$text = 'hello';
my $CustomName = convert_to_uppercase($text);
    #Uses declaration syntax each time I use the subroutine.    
print $text; #Prints: hello
print $CustomName; #Prints: HELLO

sub convert_to_uppercase {
    #Simply returns the result

    my ($content) = @_;

    return uc $content; 
}

我想使用它的原因不是每次使用子例程my $newVariable = convert_to_uppercase(param);时都要重新输入声明语法。相反,我想只使用子程序调用而没有新的变量声明语法convert_to_uppercase_new(param1,param2);我觉得它更简单,更自然。

0 个答案:

没有答案