user174912
user174912

Reputation: 21

How can I change the hostname in a URL using Perl?

I have some URLs like http://anytext.a.abs.com

In these, 'anytext' is the data that is dynamic. Rest of the URL will remain same in every case.

I'm using the following code:

$url = "http://anytext.a.abs.com";


    my $request = new HTTP::Request 'GET', $url;
    my $response = $ua->request($request);
    if ($response->is_success)
    {
        function......;
    }

Now, how can I parse a URL that has dynamic data in it?

Upvotes: 0

Views: 733

Answers (4)

draegtun
draegtun

Reputation: 22570

Not sure but is this close to what you're after?:

for my $host qw(anytext someothertext andanother) {
    my $url      = "http://$host.a.abs.com";
    my $request  = new HTTP::Request 'GET', $url;
    my $response = $ua->request($request);
    if ($response->is_success)
    {
        function......;
    }
}

Upvotes: 3

Axeman
Axeman

Reputation: 29854

I think this is probably enough:

# The regex specifies a string preceded by two slashes and all non-dots
my ( $host_name ) = $url =~ m{//([^.]+)}; 

And if you want to change it:

$url =~ s|^http://\K([^.]+)|$host_name_I_want|;

Or even:

substr( $url, index( $url, $host_name ), length( $host_name ), $host_name_I_want );

This will expand the segment sufficiently to accommodate $host_name_I_want.

Upvotes: 1

Cornelius
Cornelius

Reputation: 830

Well, like you would parse any other data: Use the information you have about the structure. You have a protocol part, followed by "colon slash slash", then the host followed by optional "colon port number" and an optional path on the host. So ... build a little parser that extracts the information you are after.

And frankly, if you are only hunting for "what exactely is 'anytext' here?", a RegEx of this form should help (untested; use as guidance):

$url =~ m/http\:\/\/(.*).a.abs.com/;
$subdomain = $1;

$do_something('with', $subdomain);

Sorry if I grossly misunderstood the problem at hand. Please explain what you mean with 'how can I parse a URL that has dynamic data in it?' in that case :)

Upvotes: 0

Powerlord
Powerlord

Reputation: 88836

Something like this maybe?

Otherwise, you can use the URI class to do url manipulation.

my $protocol = 'http://'
my $url_end = '.a.abs.com';

    $url = $protocol . "anytext" . $url_end;
    my $request = new HTTP::Request 'GET', $url;
    my $response = $ua->request($request);
    if ($response->is_success)
    {
        function......;
    }

Upvotes: 1

Related Questions