问题描述
我有一个在提示下输入的变量:
I have a variable that is entered at a prompt:
my $name = <>;
我想将一个固定的字符串 '_one'
附加到它(在一个单独的变量中).
I want to append a fixed string '_one'
to this (in a separate variable).
例如如果 $name = Smith
那么它就变成 'Smith_one'
E.g. if $name = Smith
then it becomes 'Smith_one'
我尝试了几种方法都没有得到正确的结果,例如:
I have tried several various ways which do not give me the right results, such as:
my $one = "${name}_one";
^ _one
当我打印出来时出现在下一行,当我使用它时,根本不包括_one.
^ The _one
appears on the next line when I print it out and when I use it, the _one is not included at all.
还有:
my $one = $name."_one";
^ '_one'
出现在字符串的开头.
^ The '_one'
appears at the beginning of the string.
还有:
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!
推荐答案
您的问题与字符串追加无关:当您读取一行时(例如通过 ),然后记录输入分隔符包含在那个字符串中;这通常是一个换行符
\n
.要删除换行符,chomp
变量:
Your problem is unrelated to string appending: When you read a line (e.g. via <>
), then the record input separator is included in that string; this is usually a newline \n
. To remove the newline, chomp
the variable:
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"
要将变量插入到字符串中,通常不需要使用的 ${name}
语法.这些行都会将 _one
附加到您的字符串并创建一个新字符串:
To interpolate a variable into a string, you usually don't need the ${name}
syntax you used. These lines will all append _one
to your string and create a new string:
"${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.
这会将 _one
附加到您的字符串中,并仍将其存储在 $name
中:
And this will append _one
to your string and still store it in $name
:
$name .= "_one"
这篇关于将字符串变量附加到 Perl 中的固定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!