Re: [QUIZ] Perl 'Easy' Quiz #2005-2

Luke Triantafyllidis <[email protected]> Sun, 06 Feb 2005 12:31:52 +1100
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
My Perl solutions and tests are attached. I didn't really put much 
testing into it, but they were fairly quick solutions that I wrote up at 
the last minute. I've also got a couple of Python solutions too, which, 
as far as I've tested, work for all cases.

Fairly easy in Python.

 >>> fix1 = lambda f: ''.join(f.split('.', f.count('.') - 1))
 >>> fix1('this.is.a.file.txt')
'thisisafile.txt'

 >>> fix2 = lambda f: f.replace('.', '', f.count('.') - 1)
 >>> fix2('this.is.a.file.txt')
'thisisafile.txt'


-- 
Luke Triantafyllidis
mail:    triple __at__ aeoth.net
web:     http://triple.aeoth.net
02-2005.pl (text/plain, 674 B)
#!/usr/bin/perl -w

use strict;

for('this.is.a.file.txt', 'thisisafile.txt', 'thisisafiletxt', '.thisisafiletxt', '..this..is..a..file.txt')
{
	printf "fix1: %18s : %s\n", $_, fix1($_);
	printf "fix2: %18s : %s\n\n", $_, fix2($_);
}

# splits and joins
sub fix1
{
	my $filename = shift;

	if($filename =~ /\./)
	{
		my @spl = split /\./, $filename;
		my $file = join '', @spl[0 .. $#spl - 1];
		my $ext = $spl[-1];
		return "$file.$ext";
	}
	else
	{
		return $filename;
	}
}

# regex match
sub fix2
{
	my $filename = shift;

	if($filename =~ /^(.*)\.(.*?)$/)
	{
		my ($file, $ext) = ($1, $2);
		$file =~ s/\.//g;
		return "$file.$ext";
	}
	else
	{
		return $filename;
	}
}