Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!ucbvax!iwarp.intel.com!news From: merlyn@iwarp.intel.com (Randal L. Schwartz) Newsgroups: comp.lang.perl Subject: Re: path truncation quest Keywords: path,truncation Message-ID: <1991Mar21.174954.21421@iwarp.intel.com> Date: 21 Mar 91 17:49:54 GMT References: <1991Mar21.010547.13331@convex.com> <1991Mar21.064642.29427@eng.umd.edu> Sender: news@iwarp.intel.com Reply-To: merlyn@iwarp.intel.com (Randal L. Schwartz) Organization: Stonehenge; netaccess via Intel, Beaverton, Oregon, USA Lines: 47 In-Reply-To: ziegast@eng.umd.edu (Eric W. Ziegast) In article <1991Mar21.064642.29427@eng.umd.edu>, ziegast@eng (Eric W. Ziegast) writes: | In article <1991Mar21.010547.13331@convex.com> you write: | >Any suggestions on how, given the argument "/directory/sub/100.host.0" | >that one could take off the "100.host.0" component, leaving | >"/directory/sub" ? | | At first, I thought about using an array: | | @tmp = split(/\//,$path); | $dir = join("/",pop(@tmp)); | | But in Perl, there's always a better way of doing things: | | $path =~ s/((\/[^\s\/]+)+)\/([^\s\/]+)/$1/; | | A simplified version would be: | | /((\/F)+)+)\/(F)/ | | F matches a one word file/directory name. | In my example I use [^\s\/]+ which simply matches | any word without whitespace or "/" in it. | You may want to use something more strict instead. | | $1 will match the directory path. (man dirname) | $2 is used only for /F grouping | $3 will match the base name. (man basename) | | This is, of course, only if it's a full path name. Anything else | won't match (and won't be changed). Ouch. Why not just: $path =~ s#^(/.*)/.*$#$1#; (If you have newlines in your filenames, replace "." with "(.|\n)".) The nested "+" ops aren't buying you anything, nor is the paren-pair on the right side. And .* in the left is guaranteed to match the longest string. $_ = "/Just/another/Perl/hacker,/OK?"; s#^(/.*)/.*$#$1#; y#/# #; s/^.//; print -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/