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

Hi all, I have files containing paths to files and directories. For example:
/path/to/some/file.txt /path/to/some/directory/ Now what I would like to do is write this list to another file, but in the case of directories, I would like to have them in the format: /directory/=directory/ ie, take to last directory from the full path. I've had a look at File::Spec and File::Basename but don't think they can help me!! Any help appreciated. Regards, Stacy.

Replies are listed 'Best First'.
Re: Complex string parsing
by arturo (Vicar) on Apr 25, 2001 at 04:52 UTC

    What tells you that a line corresponds to a directory? The fact that it has a slash on the end of it? Here's a regular expression that will match such entries:

    $line =~m#/$#;

    But if you have such a marker of directories already, I'm not sure why you'd need to do what you're doing. If the existence and absence of a trailing slash isn't a reliable indicator of what's a directory (or even if you can't *assume* they are), then you'll have to go to the filesystem and use the -d filetest (see this node for more info on filetest operators).

    HTH

      Hi all, thanks for your replies. I was getting stuck on the the regx for the directory match. I also put in a check to see if the path is in fact a directory. The code below does what I was after.
      open(TMP,'file.txt'); while($line = <TMP>) { chomp($line); next if $line =~ /^Total/; next if $line =~ /^\d+/; ($path) = split(/\s+/,$line); if (-d "$path") { if ($path =~ m!/$!) { $dir = (split /\//, $path)[-1]; print "/$dir/=/$dir\n"; } } } close(TMP);
      Again, many thanks! Regards, Stacy.
        Maybe you like this concise style:
        open TMP, 'file.txt'; while( <TMP> ){ chomp; next if /^Total/ or /^\d/; s/\s+//; if (-d and m!/$!){ my $dir = (split !/!)[-1]; print "/$dir/=/$dir\n"; } } close TMP;
        But of course, this is subject to taste.
        "We are not alone"(FZ) Update: greenfox pointed out that I forgot the TMP in the while condition...
Re: Complex string parsing
by greenFox (Vicar) on Apr 25, 2001 at 04:44 UTC
    If I understand the question properly, you can adopt this-
    my $path = '/path/to/some/file.txt'; my $file = '/path/to/some/directory/'; my $dir; for ($path, $file){ # if you know the dirs will always have a trailing slash # otherwise if (-d $_){ if (m!/$!){ $dir = (split /\//)[-1]; } else { # else its a file } } print $dir, "\n";

    --
    my $chainsaw = 'Perl';