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

Is there a way I can do a reverse chop/string chop?
first I will query my database and get http://www.mysite.com/images/uploads/1050084447_4.jpg
I then need my variable to end up just as 1050084447_4.jpg
in other words I need to get rid of http://www.mysite.com/images/uploads/
thanks,
Paul

Replies are listed 'Best First'.
Re: reverse chop/string chop ?
by Roger (Parson) on Oct 22, 2003 at 02:39 UTC
    You can do this without reverse or chop, with a one-liner:
    my $URL = "http://www.mysite.com/images/uploads/1050084447_4.jpg"; # retrieves the image name from the URL my $image_name = (split /\//, $URL)[-1]; print "$image_name\n";
    Which prints:
    1050084447_4.jpg

      There's no reason to use split either...

      my ($file) = $url =~ m!([^/]*)$!;

      -sauoq
      "My two cents aren't worth a dime.";
      
      works like a charm!
      thanks guys!
Re: reverse chop/string chop ?
by Aragorn (Curate) on Oct 22, 2003 at 06:44 UTC
    If you need to do more with URL's than just picking out the filename, take a look at The URI module, or more specifically: URI::URL.

    Arjen

Re: reverse chop/string chop ?
by dragonchild (Archbishop) on Oct 22, 2003 at 14:06 UTC
    I'm going to strongly second aragorn's statement, and go further. You NEED to use the URI modules, in particular, URI::Split for the uri_split() function.

    Here's the problem: What if your database is screwed up and gives you back "http://www.mysite.com" as the result? Well, with the aforementioned solutions, your imagename will be "www.mysite.com", when it should be undef. Better is something along the lines of:

    use URI::Split qw(uri_split); use File::Spec; my $url= get_url_from_database(); my ($scheme, $auth, $path, $query, $frag) = uri_split($url); die "No path in URI ($url) from database!" unless $path; my ($volume, $directory, $filename) = File::Spec->split_path($path); die "No filename in path ($path) from URI!" unless $filename;

    ------
    We are the carpenters and bricklayers of the Information Age.

    The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

    ... strings and arrays will suffice. As they are easily available as native data types in any sane language, ... - blokhead, speaking on evolutionary algorithms

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: reverse chop/string chop ?
by etcshadow (Priest) on Oct 22, 2003 at 03:48 UTC
    $url =~ s|.*/||;
    Real simple.

    ------------
    :Wq
    Not an editor command: Wq