I want to strip trailing stuff from a host name. To clarify, running this test program t1.pl:

use strict; use warnings; use Test::More; my @expected = ( [ 'abc', 'abc' ], [ 'abc.bill.com', 'abc' ], [ 'abc.bill.com.au', 'abc' ], [ 'xy42.com', 'xy42' ], [ 'x_y.com', 'x_y' ], [ 'x-y.com', 'x-y' ], [ '', '' ], [ '.', '' ], [ 'a.', 'a' ], [ '-.', '-' ], [ '_.', '_' ], [ '.a', '' ], [ 'f', 'f' ], [ 'f.1', 'f' ], [ 'f.1.2', 'f' ], [ 'f.1.2.3', 'f' ], [ 'f.1.2.3.4', 'f' ], [ 'f.1.2.3.4.5', 'f' ], [ 'f.1.2.3.4.5.67', 'f' ], [ 'ABC.123.456', 'ABC' ], ); plan tests => scalar(@expected); for my $e (@expected) { my ( $got, $exp ) = @{$e}; $got =~ s/\..*$//; is( $got, $exp, "'$e->[0]'" . ' -> ' . "'$got'" ); }

produces:

1..20 ok 1 - 'abc' -> 'abc' ok 2 - 'abc.bill.com' -> 'abc' ok 3 - 'abc.bill.com.au' -> 'abc' ok 4 - 'xy42.com' -> 'xy42' ok 5 - 'x_y.com' -> 'x_y' ok 6 - 'x-y.com' -> 'x-y' ok 7 - '' -> '' ok 8 - '.' -> '' ok 9 - 'a.' -> 'a' ok 10 - '-.' -> '-' ok 11 - '_.' -> '_' ok 12 - '.a' -> '' ok 13 - 'f' -> 'f' ok 14 - 'f.1' -> 'f' ok 15 - 'f.1.2' -> 'f' ok 16 - 'f.1.2.3' -> 'f' ok 17 - 'f.1.2.3.4' -> 'f' ok 18 - 'f.1.2.3.4.5' -> 'f' ok 19 - 'f.1.2.3.4.5.67' -> 'f' ok 20 - 'ABC.123.456' -> 'ABC'

I'm pretty sure I can assume my input is just an alphanumeric host name, for example fred42 or fred.com but not 192.0.2.16 say. I further doubt I need to deal with ports :80 or ?query or other guff. Though the above crude hack will probably be adequate for my needs, I'm interested to learn how other folks might tackle this sort of problem.


In reply to Extracting a bald host name by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.