in reply to How to get a true canonical path

I use the following:
$abs_file = File::Spec->rel2abs( $_, $directory ); $canon_file = elimupdir( $abs_file ); sub elimupdir { my $foo = shift; my( $volume, $directories, $file ) = File::Spec->splitpath(File::S +pec->canonpath( $foo )); my( @dur ) = File::Spec->splitdir( $directories ); my @dar; foreach(@dur){ if( $_ eq $updir ){ pop @dar; } else { push @dar, $_; } } return File::Spec->catpath( $volume, File::Spec->catdir( @dar ), $file ); }

pelagic

Replies are listed 'Best First'.
Re^2: How to get a true canonical path
by Anonymous Monk on Jun 21, 2019 at 09:03 UTC
    Sub is nice, here is returns relative path to current directory:
    # sub file_normalize: based on https://www.perlmonks.org/?node_id=3628 +93 sub file_normalize { use File::Spec::Functions; my $dir_ref = "."; my $file = shift; $file = File::Spec->rel2abs($file); my( $volume, $directories, $basename ) = File::Spec->splitpath(File:: +Spec->canonpath($file)); my @dirs_in = File::Spec->splitdir( $directories ); my @dirs_out; for my $dir (@dirs_in) { if ($dir eq "..") { pop @dirs_out; } else { push(@dirs_out, $dir); } } return File::Spec->abs2rel(File::Spec->catpath($volume, File::Spec->c +atdir(@dirs_out), $basename), $dir_ref); }

      Nitpicks: File::Spec::Functions doesn't need to be loaded since it isn't being used, and since File::Spec is already being used, I'd recommend File::Spec->curdir and File::Spec->updir instead of "." and "..".

      But as was already mentioned in this thread, such logical cleanups have potentially major caveats. Going out to the filesystem with Cwd's abs_path and related is generally better.