Reputation: 53
I am using split function to extract the a string from given line.
exp :
\abc\Logs\PostBootLogs\05-27-2014_17-05-51\UILogs_05-27-2014_17-05-52.txt
\abc\Logs\PostBootLogs\01-10-1970_20-33-22\01-10-1970_21-18-26\UILogs_01-10-1970_21-18-27.txt
In the above exp we need to capture string which is there between PostBootLogs and UILogs_01-10-1970_21-18-27.txt
Code :
use strict;
use warnings;
my $data = '\abc\Logs\PostBootLogs\05-27-2014_17-05-51\UILogs_05-27-2014_17-05-52.txt';
my $test1 = '\abc\Logs\PostBootLogs\01-10-1970_20-33-22\01-10-1970_21-18-26\UILogs_01-10-1970_21-18-27.txt';
my @values = split('UILogs'(split('PostBootLogs', $data)));
my @values1 = split('UILogs', $values[1]);
print "$values1[0]\n\n";
print "$test1\n\n";
my @values_1= split('PostBootLogs', $test1);
my @values1_1 = split('UILogs', $values_1[1]);
print $values1_1[0];
exit 0;
is there any better way to do this thing?
Upvotes: 0
Views: 53
Reputation: 35198
Creative use of splits. As has been demonstrated, the easiest method to do this is to use a regex.
However, if you want to see how to use splits to more cleanly accomplish this observe the following:
use strict;
use warnings;
my @data = qw(
\abc\Logs\PostBootLogs\05-27-2014_17-05-51\UILogs_05-27-2014_17-05-52.txt
\abc\Logs\PostBootLogs\01-10-1970_20-33-22\01-10-1970_21-18-26\UILogs_01-10-1970_21-18-27.txt
);
print "splits: \n";
for (@data) {
my ($vol, @path) = split /\\/;
my $subdir = join '\\', @path[3..$#path-1];
print $subdir, "\n";
}
print "regex: \n";
for (@data) {
if (/PostBootLogs\\(.*)\\UILogs/) {
print "$1\n";
} else {
warn "Data format not recognized: $_";
}
}
Outputs:
splits:
05-27-2014_17-05-51
01-10-1970_20-33-22\01-10-1970_21-18-26
regex:
05-27-2014_17-05-51
01-10-1970_20-33-22\01-10-1970_21-18-26
Upvotes: 0
Reputation: 72271
Regular expressions make this sort of thing much easier.
$data =~ m/PostBootLogs(.*?)UILogs/ or die "Misformatted data";
my $timestamps = $1;
Upvotes: 1
Reputation: 50637
You can use regex to capture between PostBootLogs\
and \UILogs
my ($captured) = $data =~ /PostBootLogs\\ (.+?) \\UILogs/x;
Upvotes: 3