>perl -wMstrict -le
"my $s = 'hostname.ms.com';
$s =~ s{ [.] .* \z }''xms;
print qq{'$s'};
"
'hostname'
| [reply] [d/l] |
Thank you AnomalousMonk (Vicar).
A few follow up questions. what is "-wMstrict -le" mean?
Also, can you explain this line a bit more?
$s =~ s{ . .* \z }''xms;
what does the \z and xms mean?
| [reply] |
When posting code, you need to wrap it in <code> tags so it doesn't get mangled - see Markup in the Monastery.
Command line switches are documented in perlrun. The switches -w, -Mstrict, -l, and -e enable warnings, strict, automatic chomps and one-liner execution respectively.
When you have questions about regular expressions, the go-to sources are perlre and perlretut. In this case, Assertions in perlre says \z Match only at end of string
and Modifiers in perlre says:
m
Treat string as multiple lines. That is, change "^" and "$"
from matching the start or end of the string to matching
the start or end of any line anywhere within the string.
s
Treat string as single line. That is, change "." to match
any character whatsoever, even a newline, which normally it
would not match.
Used together, as /ms, they let the "." match any character
whatsoever, while still allowing "^" and "$" to match,
respectively, just after and just before newlines within
the string.
x
Extend your pattern's legibility by permitting whitespace
and comments. Details in /x
See also /x.
| [reply] [d/l] [select] |
thank you Kennethk. A follow up question. I am reading that the ^. is a metacharacter to indicated beginning of the string. So is if the variable is:
hostname.ms.com
is the ^. ignoring the "hostname" part of the string and just picking up the " .ms.com "? Also, why does the ^. have to be in brackets?
| [reply] |
On the first position inside square brackets, ^ has a different meaning: it is a negation. So, [^.] means anything but a dot.
| [reply] [d/l] [select] |
Hello Everyone,
Thank you for your help. I think I found a solution. It may not be as pretty as the ones supplied (I am still researching what those special characters mean) but I think it will work. If anyone see's a flaw in this code, please let me know as I will be implementing into my production environment very soon.
Thanks,
Jaime
#my $hostname = 'name.ms.com';
my $hostname = 'name';
print $hostname;
if ($hostname =~ /\.ms.com$/) {
print "\nthis is true";
@nameparts = split(/\./,$hostname);
print "\n";
print $nameparts[0];
print "\n";
print $nameparts1;
print "\n";
print $nameparts2;
$firstpart = $nameparts[0];
print "\n";
print $firstpart;
}
else {
print "\nthis is false";
}
| [reply] |
| [reply] [d/l] [select] |