in reply to split to get the dir name

You probably want to use substr.

Plankton: 1% Evil, 99% Hot Gas.

Replies are listed 'Best First'.
Re: Re: split to get the dir name
by davido (Cardinal) on Sep 29, 2003 at 18:18 UTC
    To elaborate on the substr approach, if you know the absolute position that something occurrs within a string, substr is a lot faster and less confusing to regexp novices than a regular expression or split.

    For example, if your string looks like this:

    my $str; $str = "drwxr-xr-x 2 jonnyq jonnyq 4096 Sep 21 18:52 bin";

    And each directory item starts the 'filename' portion of the listing at the same absolute column, (in this case, 56, starting counting from 0), then you can extract everything from that column to the end of the string with:

    my $file = substr $str, 56;

    If you really want to use a regular expression, and you know that the filename always occurs at the end of the line, and that it cannot contain whitespace you can do it like I've done in the following example (which won't work if you're in a situation where filenames my contain whitespace).

    if ( $string =~ /\s(\S+)\s*$/) { print $1, "\n" };

    This method anchors your search to the end of the line (and at the same time allows trailing whitespace to be ignored). You're telling the regexp engine to match only non-space characters, preceeded by a space character, at the end of the line.

    Of course if whitespace is permitted in your file name, the regexp method becomes a lot more difficult (and split also won't work).

    Unless you're interested in each field preceeding the filename, I don't see a need for split. However, if your homework assignment requires it, you may do this:

    my $filename = (split /\s+/, $string)[-1]; print $filename, "\n";

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

      (which won't work on Win32 because Win32 filenames my contain whitespace, but works fine on Linux)

      What makes you think Linux filenames can't contain spaces?


      We're not surrounded, we're in a target-rich environment!