Most of the time you should use File::Spec to manipulate paths. It has been bundled with Perl for forever, so there's no reason not to.
use File::Spec::Functions qw(canonpath splitdir); my (@path) = splitdir canonpath $path; # @path now contains ('', 'home', 'a', 'ff.pl') print $path[2], "\n";
But just as a point of interest, you have two alternatives: a regex-only solution would be simply
my ($userhome) = ($path =~ m!^/home/([^/]+)!);
This will match a string that starts with /home/, followed by at least one character that is not a slash, and will capture all these non-slash characters. The other way would be to split on slashes:
my @path = split m!/!, $path; # @path is now ('', 'home', 'a', 'ff.pl') print $path[2], "\n";

Note how I used $path instead of your $a. This is for two reasons - first of all, $a and $b carry a special meaning for the sort function in Perl, so you shouldn't use them elsewhere. And secondly, $a is not very descriptive. Variables and functions should always have descriptive names, lest you find yourself boggling at your own code after putting it aside for two weeks.

Also note how I used m!! instead of // to delimit the regular expressions. If you explicitly mention the m, Perl allows you to pick something other than forward slashes as delimiters, so you won't need to backwhack forward slashes inside the pattern. This is very handy to avoid "leaning toothpick syndrome". This and more is described in perldoc perlop.

Makeshifts last the longest.


In reply to Re: Matching part of a path by Aristotle
in thread Matching part of a path by hweefarn

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.