agent00013 has asked for the wisdom of the Perl Monks concerning the following question:

I'm grabbing a link from HTML and fixing it to take out the /../ and replace it with the absolute address. Here's the regex part of the code and some example variables.

$base_url = "http://www.something.com/angels/devils"; $base_url =~ s!/[^/]*?$!!; #strip off the subdirectory print "$base_url \n"; $address = "http://www.something.com/angels/devils/../faries/"; $address =~ s!.*/\.\./(.*)!$base_url/$1!eg; ### stick this in &grabLinks ### print "$address \n";
Output is:
http://leto.advtech.uswest.com/SERVICES
Illegal division by zero at line 14.    #it's line 7 here...

I assume I'm doing something wrong with my formatting, but I can't figure it out. I tried adding {} brackets around the variable names but it wasn't working. Thanx for your help.

Replies are listed 'Best First'.
Re: Why am I getting a Divide by Zero error?
by davorg (Chancellor) on Jun 20, 2001 at 20:15 UTC

    The problem line is this one:

    $address =~ s!.*/\.\./(.*)!$base_url/$1!eg;

    The /e option askes Perl to execute the replacement string before using it. Perl is therefore trying to divide $base_url by $1. Presumably, when you evaluate $1 as a number it becomes zero and causes your error.

    You don't need the /e and can safely remove it.

Re: Why am I getting a Divide by Zero error?
by dimmesdale (Friar) on Jun 20, 2001 at 21:57 UTC
    $base_url =~ s!/[^/]*?$!!; #strip off the subdirectory
    Why are you using *? here? The greedy quantifier would seem to do what you want. But there's a better choice. A regex is a little bit of overkill here; you might want to check out rindex on the perl manpages, or this site. Your second regex could use a little improving too, though its hard to say what exactly could be done without knowing what $address is holding; I had some advice, but I noticed the /g on the regex. That leads to the idea that there are many addresses there(and that you should be careful with .* then, unless they are separated by \n's).