Reputation: 19
I have a variable that contains a path like this:
$Path = "C:/Work/Job_V14/Myfile";
This variable can change each time I run the code. The only thing that never changes is that in the Path I will always have _V and 2 digit (like in this case _V14).
How can I obtain from the path only the part _V+2 digit?
Upvotes: 0
Views: 100
Reputation: 6818
Please see the following piece of code
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
while( <DATA> ) {
say $1 if m!(_V\d{2})/!;
}
__DATA__
C:/Work/Job_V14/Myfile
C:/Work/Project_01/Job_V12/SomeFile
C:/Work/Project_03/Job_V02/SomeFile
C:/Work/Job_V34/SomeFile
Output:
_V14
_V12
_V02
_V34
Upvotes: 0
Reputation: 71
$Path = "C:/Work/Job_V14/Myfile";
# this code makes the assumption that your _Vxx contains the first _ in the path string
my $first; my $second; my $result ;
($first, $second) = split('_',$Path,2); # split off the part before _
($result) = split('/',$second) ; # takes only the first element
$result = "_" . $result ; #adding back the _
print $result . "\n" ; # prints _V14
If you have multiple occurrences of _ before your _Vxx, then this code needs an adjustment.
Upvotes: 1
Reputation: 3735
You can use a regular expression to match the substring, like so
$Path = "C:/Work/Job_V14/Myfile";
if ( $Path =~ m[ ( _V \d\d [/\\] ) ]x )
{
my $match = $1 ;
print "Matched '$match'\n";
}
else
{
print "No match\n";
}
Above assumes that _V+2digit can never appear anywhere else in the string. If that is the case, the regular expression needs to be revisited.
Upvotes: 1
Reputation: 386706
If the path will always be a file in the directory whose name you want, I'd start with the following:
use Path::Class qw( file );
my path = "C:/Work/Job_V14/Myfile";
my $project = file($path)->dir->basename; # Job_V14
Now, we us a match to extract the version.
my ($version) = $project =~ /_V(\d+)\z/; # 14
Upvotes: 2