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

my $filename2 = "apple.htm"; my $filename2 =~ s/^[^.]*(\.[\w]+$)/$1/;
My problem is that I wanna just get the .htm off apple, but my regex wont work, very frustrating.

Replies are listed 'Best First'.
Re: Regex Problems
by sauoq (Abbot) on Nov 07, 2002 at 23:57 UTC

    There is no need for the second my. The variable has already been declared. When you redeclare the variable it is undefined so your substitution is meaningless. Once you fix that, your substitution is wrong also. It attempts to replace the whole filename with the extension because that's the part you are capturing in $1. Try this as your second line:

    $filename2 =~ s/\.[^.]*$//;
    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Regex Problems
by robartes (Priest) on Nov 08, 2002 at 00:05 UTC
    a regexp that will strip everything but the extension (if that's what you're trying to do - you are a bit unclear) is:
    use strict; my $filename="camel.flea"; $filename=~s/\w+(\.\w+)$/$1/; # Warning: untested
    But for filename manipulations such as the ones you're doing, I would recommend File::Basename. No need to reinvent the wheel with the risk of inventing a square one...

    CU
    Robartes-

Re: Regex Problems
by Ananda (Pilgrim) on Nov 08, 2002 at 04:19 UTC
    This should be of help.

    my $file = "apple.htm"; $file =~ s/^(.*)\.(.*)$/$1/; print "\$file = $file\n";

    Explanation: The initial (.*) in s/^(.*)\.(.*)$/$1/; evaluates any string before the "." character and $1 representing this string char replaces the initial value assigned to the $file variable.

    Anandatirtha

Re: Regex Problems
by hackdaddy (Hermit) on Nov 08, 2002 at 02:50 UTC
    Try this:
    my $f = "apple.htm"; $f =~ s/^(\w+)\.(\w+)$/$1./; print "\$f = $f\n";