in reply to how to expand home directory ~

If ~ really is hardcoded in the script, you'll need to expand it first. perlfaq5 has a nice regex for doing just that:

$filename = "~/madam"; $filename =~ s{ ^ ~ # find a leading tilde ( # save this in $1 [^/] # a non-slash character * # repeated 0 or more times (0 means me) ) }{ $1 ? (getpwnam($1))[7] : ( $ENV{HOME} || $ENV{LOGDIR} ) }ex; print $filename, "\n";
-derby
Update and to combine the regex with your code:
#!/usr/bin/perl use strict; use File::Spec; my $str = " /home/madam ~madam ~/madam"; my @strarray = split(" ",$str); for (@strarray){ my $file = expand_tilde( $_ ); if ( -d $file ){ print "path present : $file\n"; } else { print "path not present : $file\n"; } } sub expand_tilde { my( $file ) = shift; $file =~ s{ ^ ~ # find a leading tilde ( # save this in $1 [^/] # a non-slash character * # repeated 0 or more times (0 means me) ) }{ $1 ? (getpwnam($1))[7] : ( $ENV{HOME} || $ENV{LOGDIR} ) }ex; $file }

Replies are listed 'Best First'.
Re^2: how to expand home directory ~
by PodMaster (Abbot) on Jun 02, 2005 at 12:30 UTC
    Probably the same thing as File::Path::Expand

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

      They're pretty close but it looks like File::Path::Expand chokes on the simple cases of ~name and just ~. Not that the perlfaq regex is any better, it chokes when $ENV{HOME} and $ENV{LOGDIR} are not set. A better approach would be something along the lines of:

      $file =~ s{ ^ ~ # find a leading tilde ( # save this in $1 [^/] # a non-slash character * # repeated 0 or more times (0 means me) ) }{ $1 ? (getpwnam($1))[7] : (getpwuid($<))[7] }ex;
      -derby