Alan W. Smith
Alan W. Smith

Reputation: 25425

Is there a better way to remove a string for an array of strings in 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?

Upvotes: 2

Views: 169

Answers (3)

ikegami
ikegami

Reputation: 385655

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";

Upvotes: 6

HazySmoke
HazySmoke

Reputation: 365

I suggest using the map function. It applies an action to every element in an array. You can condense the for-loop into just one line:

map s{http://}{}, @test_array;

Also, as a side note, an easier way of printing the array contents in space-separated format is to simply put the array inside a double-quoted string:

print "@test_array";

Upvotes: 0

ErikR
ErikR

Reputation: 52039

You don't need the assignment in this line:

($test_array[$i] = $test_array[$i]) =~ s{http://}{};

you can just use:

$test_array[$i] =~ s{http://}{};

For even less typing, take advantage of the $_ variable:

for (@test_array) {
  s{http://}{};
}

Upvotes: 5

Related Questions