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


In reply to Re: Re: split to get the dir name by davido
in thread split to get the dir name by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.