在 Perl 中将字符串变量附加到固定字符串 [英] Appending a string variable to a fixed string in Perl

查看:27
本文介绍了在 Perl 中将字符串变量附加到固定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!

推荐答案

您的问题与字符串追加无关:当您读取一行时(例如通过<>),然后记录输入分隔符在该字符串中包含;这通常是换行符 .要删除换行符,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 . 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
"
    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 中将字符串变量附加到固定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆