简体   繁体   English

将split作为参数传递给拼接

[英]Passing split as parameter to splice

I need the first two names only in a string. 我只需要字符串中的前两个名称。

my $myNames = "Jacob, Michael, Joshua, Matthew, Ethan, Andrew";

my $meNewNames = join ( ',',splice( split(/,/,$myNames), 0, 2));

Please rectify me if anything wrong in it or we can achive it in another way. 如果有任何问题,请纠正我,否则我们可以通过其他方式解决。

print "$meNewNames\\n";

It throws the error. 它引发错误。 Type of arg 1 to splice must be array (not split) 要拼接的arg 1的类型必须为数组(不能拆分)

Thanks. 谢谢。

Well, like the error says, the first argument must be an array. 好吧,就像错误所说的那样,第一个参数必须是一个数组。 The possible solutions: 可能的解决方案:

my $meNewNames = join ( ',',splice( [ split(/,/,$myNames) ], 0, 2)); 

Make an anonymous array reference out of your split return values. 从拆分的返回值中创建一个匿名数组引用。 However, this only works in perl version 5.14 and up. 但是,这仅在perl版本5.14及更高版本中有效。 You can do it more simply like this: 您可以像这样更简单地进行操作:

my $meNewNames = join ( ',', (split(/,/,$myNames))[0,1] ); 

Use a subscript to take the first two values of your split. 使用下标获取拆分的前两个值。 In this style, it is perhaps more readable to do: 用这种样式,可能更容易阅读:

my @names = split /,\s*/, $myNames;
my $meNewNames = join ',', @names[0,1];

This is simpler: 这比较简单:

my $meNewNames = join ( ',', (split(/,/,$myNames))[0,1] );

Also, you can use a regexpr instead of join / split: 另外,您可以使用regexpr代替join / split:

$myNames =~ m!(\w+, *\w+)!;
# $1 => Jacob, Michael;

You're giving an anonymous list to split , but you really need a real array. 您要提供一个匿名列表进行split ,但是您确实需要一个真实的数组。 Here's one way of fixing this: 这是解决此问题的一种方法:

   my @array = split(/,/,$myNames);
   my $meNewNames = join ( ',',splice( @array, 0, 2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM