For example I have this array
my @a = ("http://aze.com/azfaz", "http://acc.com/azfssz");
I want to remove the azfaz
/azfssz
part in the URLs without using foreach
I made this subroutine to remove the last section after the 3 slash /
characters
sub cheat {
my @o = split( /\//, $_[0], 3 );
my @r = split( /\//, $o[2], 0 );
return $r[0];
}
When I call cheat(@a)
it just removes the azfaz
from the first site in array and it's not working for the other
答案 0 :(得分:7)
您应该使用URI
模块来操作URL字符串
喜欢这个
use strict;
use warnings;
use 5.010;
use URI;
my @a = qw< http://aze.com/azfaz http://acc.com/azfssz >;
sub host_name {
return map { URI->new($_)->host } @_;
}
say for host_name @a;
aze.com
acc.com
答案 1 :(得分:3)
$_[0]
只是引用传递给cheat
的数组中的第一个元素。您的处理算法看起来正确,您只需将其应用于@_
中的所有元素即可。有许多方法可以迭代列表以生成另一个列表。 map
通常是一种好方法:
sub cheat {
return map {
my @o = split(/\//,$_,3); # split on $_, not $_[0]
my @r = split (/\//,$o[2],0);
$r[0]; # add to map output, don't return
} @_;
}
或者您可以保留现有的cheat
功能,并在功能之外运行map
。
@fixed_array = map { cheat($_) } @array;
foreach
也会奏效 - 但您似乎不愿意出于某种原因使用它。