2

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?

3 Answers 3

6

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";
Sign up to request clarification or add additional context in comments.

1 Comment

This is great for the specific case I outlined. I was just using that as an example and am really looking for the generic way to deal with strings in arrays. I should have made that clearer in the question.
5

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://}{};
}

1 Comment

Picking this one since it shows how to deal with strings in general. For something that needs the "http://" removal that I was using as my example case, the answer from ikegami is also worth checking out.
0

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

2 Comments

Most people cringe at using map as a topicalizer. s{http://}{} for @test_array; is preferred.
map is meant to be used as a list operator. It maps one list to another - hence the name. There is no advantage to using it over the ordinary for, which avoids misappropriating the concept of a mapping, and results in clearer code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.