remove a part in array value without foreach

时间:2015-07-31 20:55:29

标签: arrays perl

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

2 个答案:

答案 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也会奏效 - 但您似乎不愿意出于某种原因使用它。