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

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

本文介绍了在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'

我尝试了几种无法给我正确结果的方法,例如:

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'出现在字符串的开始

并且:

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中将字符串变量附加到固定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:49