Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delaying a split

Status
Not open for further replies.

HughbertD

Technical User
Apr 30, 2007
42
GB
Hi,

I have a string in a scalar $path , I want to split it to get just the file name. I was splitting on the "/" into an array, and then "popping" the last element of the array into the variable, but is there a simpler way to do this?
 
Still uses a split, but it's quicker than creating a wasted array.

Code:
my $filename = (split '/', $path)[-1];

- George
 
Excellent - so the [-1] is telling it to split one from the end?
 
Nope. It's a list slice. The "split" function creates a list of scalars. The [-1] indicates that you only want the one on the end. It doesn't affect what "split" is doing at all.

A more standard way of doing this would be to use the "basename" function in the standard File::Basename module, i.e.:
Code:
use File::Basename;
my $path = '/home/ishnid/foo';
print basename( $path ),"\n";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top