SPUG: better way?

Ken McGlothlen mcglk at serv.net
Tue Aug 10 17:02:15 CDT 1999


Sean Ruddy <sean at DigiDot.com> writes:

| Better way to get just the domain from referer?
| I think this code will show my newbieness (but it works...)
| <HACK>
|  my $re = referer();
|  my $doubleslash = rindex($re,'//');
|  my $headslash = substr($re,$doubleslash+2);
|  my $domslash = index($headslash,'/');
|  print substr($headslash,0,$domslash);
| </HACK>

Yes, that works.  But you might be better off with a regex:

	sub urldomain {
	    $_ = shift;
	    m|^http://([^/]+)|;
	    return( $1 );
	}

Then you can call it with something like

	my $dom = &urldomain( $re );

In recognition that this is new for you, let's go over that routine line by
line.

	sub urldomain {			# Well, almost line by line.  That one
					# shouldn't be so hard to figure out.

	    $_ = shift;			# This takes the first parameter passed
					# in, and assigns it to the special
					# variable "$_", which is used as the
					# default variable for the match
					# function, used in the next line.  I'm
					# going to replace this line with
					# another perfectly legal Perl usage.

	    m|^http://			# The string has to start with http://
		(			# Save whatever matches next in $1
		    [^/]+		# One or more characters which aren't /
		)			# That ends $1
	    |x;				# And that ends the match, with a
					#  modifier that allows us to put in
					#  whitespace and comments in the
					#  regexp.

					# Remember that if we don't bind the
					# match operator with the =~ operator,
					# it automatically acts on $_.

	    return( $1 );		# Now we return what we got as $1.
	}

You could make this more general by replacing the "http" with "[a-z]+", which
would match "http", "ftp", "gopher" or any other string consisting entirely of
one or more lowercase alphabetic characters.

							---Ken

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    POST TO: spug-list at pm.org        PROBLEMS: owner-spug-list at pm.org
 Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/
 SUBSCRIBE/UNSUBSCRIBE: Replace ACTION below by subscribe or unsubscribe
        Email to majordomo at pm.org: ACTION spug-list your_address





More information about the spug-list mailing list