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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to extract from file path 2

Status
Not open for further replies.

ptsri1954

Technical User
Dec 11, 2003
5
IN
I have been trying to extract part of a file path..and so far have been unsuccessful.

I have the following:
my $verpath = \main\branch1\13

I need to extract the "branch1" from this path.

I am using the following split "formula":
my $filename1 = (split /\//, $verpath)[-1];

However this returns \main\branch1\13..instead of branch1.

The $verpath value can vary..some examples:
\main\branch1\12 - need to extract branch1
\main\branch1\sub-branch1\34 - need to extract sub-branch1
\main\intg1\branch2\branch3\45- need to extract branch3

Any help in this would be appreciated.
-Thanks
 
Looks like you are splitting on the wrong data. You have backslashes but you are splitting on forward slashes.

Code:
split /\//
vs
Code:
split /\\/

That should solve your 'branch1' problem.

I would handle 'which path to get' by counting total elements and then subtract what you are looking for. So if you know the path you want is always second to last you can just say

@path = split /\//, $verpath ;
$branch = $path[scalar(@path)-2]; # -2 since scalar returns 1 based and array is zero based)

Anyhow, its one thought. Syntax might be slightly off, I am not running it here just brainstorming.

 
Code:
#!perl
use strict;
use warnings;

while (<DATA>) {
    my $x = (split /\\/)[-2];
    print "$x\n";
}

__DATA__
\main\branch1\12
\main\branch1\sub-branch1\34
\main\intg1\branch2\branch3\45
Output:
Code:
branch1
sub-branch1
branch3

 

Siberian and Mikevh,
Thanks for the tips and code snippets..
They helped me get a better insight on split function usage.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top