Perl-related stuff and beyond (but not much)

Thursday, May 07, 2009

Extract base path

Simple solution to a Delphi task: extract base path from two paths:



#!/usr/bin/perl

# extract_base_path.pl - extract base path from two paths
# http://delphi.about.com/b/2009/05/06/delphi-programming-challenge-extractbasepath.htm
# dprelec, 2009-05-07

use strict;
use warnings;

my $path1 = '/usr/bin/perl/lib/';
my $path2 = '/usr/bin/perl/';

my @parts = split('/', $path1);
my $last = '';
my $re = join('|', reverse map { $last .= $_ . '/'; $last } @parts);

if ($path2 =~ /($re)/) {
print $1, "\n";
}

3 comments:

rjbond3rd said...

Interesting! As an alternative appraoch, what about determining which path is shorter, then iteratively shortening the shorter path until a regex matches?

Something like this (very roughly):

#!/usr/bin/perl

my $longer = '/usr/local/apache/htdocs/';
my $shorter = '/usr/bin/';

while ($longer !~ /^$shorter/){
$shorter =~ s|[^\/]*/$||;
}

print $shorter;

darko said...

@rjbond3rd: I feel there must be a simple solution to this via regular expression only. Something like:

if ($path1 =~ /($magic$path2)/) { say $1; }

Raimon Grau said...

Another approach, using Text::Abbrev

#!/usr/bin/perl
use Text::Abbrev;
use strict;
use warnings;

my $str1 = '/usr/bin/perl/lib/';
my $str2 = '/usr/bin/perl/lub/';

my %hash = abbrev ($str1, $str2);
(keys %hash)[0] =~m[^(.*/)] ;
print $1,"\n";