Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to remove a string for an array of strings in perl?

Tags:

arrays

regex

perl

I have a Perl array of URLs that all contain "http://". I'd like to remove that string from each one leaving only the domain. I'm using the following for loop:

#!/usr/bin/perl

### Load a test array
my @test_array = qw (http://example.com http://example.net http://example.org);

### Do the removal
for (my $i=0; $i<=$#test_array; $i++) {
    ($test_array[$i] = $test_array[$i]) =~ s{http://}{};
}

### Show the updates
print join(" ", @test_array);

### Output: 
### example.com example.net example.org

It works fine, but I'm wondering if there is a more efficient way (either in terms of processing or in terms of less typing). Is there a better way to remove a given string from an array of strings?

like image 902
Alan W. Smith Avatar asked Jan 22 '26 11:01

Alan W. Smith


1 Answers

When I parse uris, I use URI.

use URI qw( );
my @urls = qw( http://example.com:80/ ... );
my @hosts = map { URI->new($_)->host } @urls;
print "@hosts\n";
like image 198
ikegami Avatar answered Jan 25 '26 03:01

ikegami