string 在 Perl 中将字符串变量附加到固定字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12459395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:36:23  来源:igfitidea点击:

Appending a string variable to a fixed string in Perl

stringperlappend

提问by dgBP

I have a variable that is entered at a prompt:

我有一个在提示下输入的变量:

my $name = <>;

I want to append a fixed string '_one'to this (in a separate variable).

我想为此附加一个固定字符串'_one'(在一个单独的变量中)。

E.g. if $name = Smiththen it becomes 'Smith_one'

例如,如果$name = Smith它变成'Smith_one'

I have tried several various ways which do not give me the right results, such as:

我尝试了几种不同的方法,但没有给我正确的结果,例如:

my $one = "${name}_one";

^ The _oneappears on the next line when I print it out and when I use it, the _one is not included at all.

^_one打印出来时出现在下一行,当我使用它时, _one 根本不包括在内。

Also:

还:

my $one = $name."_one";

^ The '_one'appears at the beginningof the string.

^'_one'出现在字符串的开头

And:

和:

my $end = '_one';
my $one = $name.$end;
or 
my $one = "$name$end";

None of these produce the result I want, so I must be missing something related to how the input is formatted from the prompt, perhaps. Ideas appreciated!

这些都没有产生我想要的结果,所以我必须遗漏一些与提示中输入的格式有关的东西,也许。想法赞赏!

回答by amon

Your problem is unrelated to string appending: When you read a line (e.g. via <>), then the record input separator is includedin that string; this is usually a newline \n. To remove the newline, chompthe variable:

您的问题与字符串追加无关:当您读取一行(例如 via <>)时,记录输入分隔符包含在该字符串中;这通常是一个换行符\n。要删除换行符,chomp变量:

    my $name = <STDIN>; # better use explicit filehandle unless you know what you are doing
    # now $name eq "Smith\n"
    chomp $name;
    # now $name eq "Smith"

To interpolate a variable into a string, you usually don't need the ${name}syntax you used. These lines will all append _oneto your string and create a new string:

要将变量插入到字符串中,通常不需要使用的${name}语法。这些行都将附加_one到您的字符串并创建一个新字符串:

    "${name}_one"  # what you used
    "$name\_one"   # _ must be escaped, else the variable $name_one would be interpolated
    $name . "_one"
    sprintf "%s_one", $name
    # etc.

And this will append _oneto your string and still store it in $name:

这将附加_one到您的字符串并仍将其存储在$name

    $name .= "_one"