Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 是否有一个班轮来获取拆分的第一个元素?_Perl - Fatal编程技术网

Perl 是否有一个班轮来获取拆分的第一个元素?

Perl 是否有一个班轮来获取拆分的第一个元素?,perl,Perl,而不是写: @holder = split /\./,"hello.world"; print @holder[0]; 有没有可能只做一个衬里就可以得到第一个元素的分裂?比如: print (split /\./,"hello.world")[0] 在尝试第二个示例时,出现以下错误: print (...) interpreted as function at test.pl line 3. syntax error at test.pl line 3, near ")[" 你应该试试你

而不是写:

@holder = split /\./,"hello.world"; 
print @holder[0];
有没有可能只做一个衬里就可以得到第一个元素的分裂?比如:

print (split /\./,"hello.world")[0]
在尝试第二个示例时,出现以下错误:

print (...) interpreted as function at test.pl line 3.
syntax error at test.pl line 3, near ")["

你应该试试你的直觉。这就是怎么做的

my $first = (split /\./, "hello.world")[0];
您可以使用仅获取第一个字段的列表上下文赋值

my($first) = split /\./, "hello.world";
要打印它,请使用

print +(split /\./, "hello.world")[0], "\n";

加号的出现是因为句法上的歧义。它表示以下所有内容都是打印的参数。报告解释道

注意不要在print关键字后面加左括号,除非您希望相应的右括号终止print的参数;在所有参数周围加上括号(或插入一个
+
,但这看起来不太好)

在上面的例子中,我发现
+
的例子更易于编写和阅读。YMMV

在尝试第二个示例时,出现以下错误: test.pl第3行附近的语法错误“[”

否,如果您按照应该的方式启用了警告,则会得到:

print (...) interpreted as function at test.pl line 3.
syntax error at test.pl line 3, near ")["

这应该是您的问题的一个重要线索。

如果您坚持使用
split
进行此操作,那么您可能会将长字符串拆分为多个字段,只会丢弃第一个字段以外的所有字段。
split
的第三个参数应用于限制要拆分字符串的字段数

my $string = 'hello.world';

print((split(/\./, $string, 2))[0]);
但我相信正则表达式可以更好地描述您想要做的事情,并完全避免这个问题

或者

my $string = 'hello.world';
my ($first) = $string =~ /([^.]+)/;


将为您提取第一个非点字符字符串。

啊,我要的是+。它不仅适用于打印,也适用于变量赋值。非常感谢。使用+插入看起来很不错,而且比括号少键入。你说得对!我扫描输出太快了,没有注意到第一行。我我加进去。
my $string = 'hello.world';
my ($first) = $string =~ /([^.]+)/;
my $string = 'hello.world';
print $string =~ /([^.]+)/;