Reputation: 11
I have to remove the first part of a dot-separated string. Such as:
test.domain.com --> domain.com
sub.domain.example.com --> domain.example.com
bar.foo.bar.hoster.net --> foo.bar.hoster.net
and so on...
How to do this in perl?
Upvotes: 0
Views: 1346
Reputation: 6553
A non-regex* solution might be more obvious:
use strict;
use warnings;
use 5.010;
my @tests = (
'test.domain.com',
'sub.domain.example.com',
'bar.foo.bar.hoster.net',
);
for my $t (@tests) {
(undef, my @parts) = split(/\./, $t);
say join('.', @parts);
}
Or:
for my $t (@tests) {
my $i;
say join('.', grep { ++$i > 1 } split(/\./, $t));
}
* Well, mostly non-regex, anyway. The first argument to split
is a pattern, but we're just matching a literal dot.
Upvotes: 1
Reputation: 85767
The easiest way is to use a substitution like this:
$str =~ s/^[^.]*\.//;
The regex means:
^
- beginning of string[^.]*
- 0 or more characters that are not .
\.
- a literal dotThere's no need to capture the rest of the string just to replace it back in.
This code assumes that if there are no dots in the string, you want to leave it unchanged.
However, if you want "foo"
to turn into ""
, you just need to make the \.
optional:
$str =~ s/^[^.]*\.?//;
Upvotes: 1
Reputation: 5274
This should do the trick:
use strict;
use warnings;
my @domains = ("test.domain.com", "abc.sub.example.com");
foreach my $value (@domains) {
$value =~ s/[^.]+.(.*)/$1/;
print $value . "\n";
}
I like using a negative character class [^.]+ (not dot) vs doing a .? Using .? seems to get me in trouble from time to time, when the character class is doing what is really being asked, up to the first non dot.
Output:
domain.com
sub.example.com
Upvotes: 0