steelcityamir
steelcityamir

Reputation: 1218

Perl regex capture grouping

Is there a better way to write the below code using a regex capture grouping?

I'm looking to get the folder name immediately after Recordings.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $path1 = '\\server1\Recordings\AU-AR-Online\Outbound\20160120\52031\52031-14-07-16.wav';
my $path2 = '\\server2\e$\Recordings\SU-AC-Online\Outbound\20160120\52031\52031-14-07-16.wav';

my @paths = ( $path1,$path2 );

foreach my $path (@paths) {
  # Split path into fields
  my @array = (split /\\/, $path);

  # Get index of Recordings
  my( $index )= grep { $array[$_] eq "Recordings" } 0..$#array;

  # Brand always follows Recordings
  print $array[$index+1];

 }

Upvotes: 1

Views: 66

Answers (2)

elcaro
elcaro

Reputation: 2297

Capture the folder directly after Recordings\

my ($brand) = $path =~ m{ Recordings \\ ( [^\\] + ) }x )

Using the x modifier on the regex means whitespace is ignore, which can help make the regex more readable.

If the brand folder is always 5th-last, you could split the path and grab it by negative indexing.

my $brand = (split /\\/, $path)[-5];

But again, that only works if the brand is always 5th last. I don't know what your data set is.

Also, if your working with paths, there are many modules (such as Path::Tiny) that make it easier to get parent/child/absolute paths, basenames, etc.

Upvotes: 1

Sean
Sean

Reputation: 29772

Sure, just replace the content of your loop with this:

my ($brand) = $path =~ m|\\Recordings\\([^\\]+)| or die "Not found";
print $brand;

Upvotes: 2

Related Questions