Jill448
Jill448

Reputation: 1793

perl regex to match string starting with pattern

I have the below perl code. I am trying to set the flag to 1 if my $location has string /foo/HELLO, which is working fine. But now I want to set the flag to 0 if $location has /foo/* (it has /foo/ and anything after it except HELLO)

How can I frame my regex in else condition to achieve it?

use strict;
use warnings;

my $flag =0;

my @locations= (
  "/path/with/foo/HELLO",
  "/path/with/foo/def-abc-addons.install",
  "/path/with/foo/def-abc-addons.lintian-overrides",
  "/path/with/foo/def-abc-addons.postrm",
  "/abc/def/ggfg",
  "/frgrg/hjytj/dgth",
);

foreach my $location(@locations){
   if ($location =~ m/\/foo\/HELLO/) {
       print 'match';
       $flag=1;
    } else {
      print 'no match';
      $flag=0
    } 
 }  

Upvotes: 0

Views: 215

Answers (3)

Borodin
Borodin

Reputation: 126722

I think what you're looking for is to filter those files that have /foo/ but not /foo/HELLO/ within the path. You can do that with the grep operator, as below

This code needs more work if your requirement is tighter than you describe. There are many edge cases and pitfalls here, and none of them are addressed. For instance, if the path contains /foo/HELLONWHEELS then it will be rejected, and that may or may not be your intention

use strict;
use warnings;
use 5.010;

my @locations= qw(
  /path/with/foo/HELLO
  /path/with/foo/def-abc-addons.install
  /path/with/foo/def-abc-addons.lintian-overrides
  /path/with/foo/def-abc-addons.postrm
  /abc/def/ggfg
  /frgrg/hjytj/dgth
);

say for grep m{ /foo/ (?!HELLO) }x, @locations;

output

/path/with/foo/def-abc-addons.install
/path/with/foo/def-abc-addons.lintian-overrides
/path/with/foo/def-abc-addons.postrm

Upvotes: 0

dawg
dawg

Reputation: 103744

You can use grep and map to construct a hash of the strings and the associated flag values:

use strict;
use warnings;

use Data::Dumper qw(Dumper);

my @locations= (
  "/path/with/foo/HELLO",
  "/path/with/foo/def-abc-addons.install",
  "/path/with/foo/def-abc-addons.lintian-overrides",
  "/path/with/foo/def-abc-addons.postrm",
  "/abc/def/ggfg",
  "/frgrg/hjytj/dgth",
);

my %h = map { $_ =~ m|/foo/HELLO| ? ($_ => 1) : ($_=>0)  } grep {m|/foo/\w+|} @locations;

print Dumper \%h;

Now %h:

    {
      '/path/with/foo/def-abc-addons.install' => 0,
      '/path/with/foo/def-abc-addons.lintian-overrides' => 0,
      '/path/with/foo/def-abc-addons.postrm' => 0,
      '/path/with/foo/HELLO' => 1
    };

Just change the regex's to suit what you are trying to accomplish.

Upvotes: 0

choroba
choroba

Reputation: 241788

You are in else, so you already know it doesn't have /foo/HELLO. So just verify /foo/ is still there:

} elsif ($location =~ m=/foo/=) {

Upvotes: 2

Related Questions