0

I need to validate a string like "[one.two.three]", where titles are separated by ".", there has to be a minimum of at least one title. Each title needs to be extracted. Is there any way to do this in a loop or does it have to be two separate steps?

use strict;
use warnings;

my @tests = ("[one]", "[two.three.four]");

foreach (@tests) {
    while ($_ =~ /^\[(\w+)(?:\.\w+)*\]$/) {
        print "$1\n";
    }

    print "\n\n\n";
}
1
  • Totally didn't think of split(). So basically use regex to validate format and allowed characters and then split for each group. Commented Feb 4, 2014 at 2:16

1 Answer 1

2

Yes, it makes sense to separate the validation and extraction:

my ($titles) = $input =~ /^\[((?:\w+|\b\.\b)+)\]\z/
    or die "invalid input $input.\n";
my @title = split /\./, $titles;

Though you could do it all at once, I think the readability suffers:

my @title = split /\./, ( $input =~ /^\[((?:\w+|\b\.\b)+)\]\z/ )[0] // ''
    or die "invalid input $input.\n";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.