Perl 字符串连接问题

Perl 字符串连接问题,perl,string,Perl,String,你能看看我下面的代码吗 #!C:\Perl\bin\perl.exe use strict; use warnings; use Data::Dumper; my $fh = \*DATA; my $str1 = "listBox1.Items.Add(\""; my $str2 = "\")\;"; while(my $line = <$fh>) { $line=~s/^\s+//g; print $str1.$line.$str2;

你能看看我下面的代码吗

#!C:\Perl\bin\perl.exe 
use strict; 
use warnings; 
use Data::Dumper;  

my $fh = \*DATA;  
my $str1 = "listBox1.Items.Add(\"";
my $str2 = "\")\;";

while(my $line = <$fh>)
{
    $line=~s/^\s+//g;

    print $str1.$line.$str2;

    chomp($line);

}


__DATA__  
Hello
 World
样式错误。我想要下面的款式。我的代码有什么问题吗?谢谢

D:\learning\perl>test.pl
listBox1.Items.Add("Hello");
listBox1.Items.Add("World");
D:\learning\perl>

$line
中读取的行有一个尾随的
换行符。你需要使用
chomp
来摆脱它。您已经在代码中输入了chomp,但它放错了位置。将其移动到循环的开始处,如下所示:

while(my $line = <$fh>)
{
    chomp($line);                 # remove the trailing newline.
    $line=~s/^\s+//g;             # remove the leading white space.
    print $str1.$line.$str2."\n"; # append a newline at the end.
}
要删除字符串中的尾随(结束)空格,请执行以下操作:

$str =~s/^\s+//;
$str =~s/\s+$//;
$str =~s/^\s+|\s+$//g;
要删除字符串中的前导空格和尾随空格,请执行以下操作:

$str =~s/^\s+//;
$str =~s/\s+$//;
$str =~s/^\s+|\s+$//g;

考虑一下打印和咀嚼之间的顺序;)

数据库连接到底在哪里@Paulo,我将标记从连接字符串修改为字符串。:-)为“连接”->“连接”编辑的标题。这与您的主要问题无关,但请记住,
print
与许多Perl函数类似。它需要一个参数列表。与其串联几个参数,然后将一个参数传递给
print
,不如直接传递它们。如下所示:
打印$str1、$line、$str2,“\n”
。我认为问题出在选择新行字符的正则表达式上。请查看所需的响应。@unicoraddit再次感谢您。实际上,我正在开发一个C应用程序,顺便说一句,我想借助Perl简化我的C代码。:-)@UnicorAddict:如何删除结尾空白?然后我可以像这样处理结尾的空白,listBox1.Items.Add(“Hello”);谢谢,最后一个不太好。您需要
s/^\s+|\s+$//g
来确保删除前导空格和尾随空格