Hi all, I'm relatively new to Perl and particularly new to regular expressions.

This is really simple script I've just mocked up. All it does is to take the input string and check if it's in the correct format or not.

Here are some examples of correct format (will always be three letters followed by a '-' followed by three numbers):
TJD-111
IIS-193
XTT-920
If a user enters input without the '-' E.g:
JDJ222
XTT920
Then add a '-' between the characters/numbers.

Simple eh?

use strict;
print "Enter Defect Number: ";
my $text = <STDIN>;

if ($text =~m/-/)
{
	print "the input is correct\n";
        # do some other stuff
}
else
{
	print "The string needs a minus \n";
        # In this case, append the '-'
}

Okay, I've worked out a pretty ropey solution. It's not great but it kinda does what I want for now.

print "Enter Defect Number: ";
my $text1 = <STDIN>;
chop($text1);

if((length($text1) < 8))
{
	if ($text1 =~m/-/)
	{
		print "the string is correct\n";
	}
	else
	{
		if((length($text1) < 7))
		{
			print "The string needs a -\n";
			my $pre = substr($text1, 0, -3);
			my $post = substr($text1, -3, 5);
			print "$pre". '-' .$post. "\n";
		}
	}
}
else
{
	print "bad input\n";
	exit;
}

I'd welcome a better solution. Cheers

use strict;
use warnings;

print "Enter Defect Number: ";
my $text1 = <STDIN>;
chomp($text1);

### Syntax : ( Condition ) ? ( True Statement ) : ( False Statement);
 
print "\n", ($text1=~ m{^([a-z]{3}\-\d{3})$}i)?     # Condition 1 
            "The string is correct\n" :             # True Statment 1
            (($text1=~ m{^(([a-z]{3})(\d{3}))$}i)?  # Condition 2
            "The sting needs - \n$2-$3" :           # True Statement 2 
            "Bad input");                           # False statement of condition 1 & 2

That's fantastic. Thanks for your help.

Can you just explain to me this line:

($text1=~ m{^([a-z]{3}\-\d{3})$}i)?

I see that first, your checking that the first three chars must be letters. What does the \d mean? and also the i? I can't see how it checks that the last three characters are numbers?

# code : ($text1=~ m{^([a-z]{3}\-\d{3})$}i)?

=~ m{}    -> is a bind variable use to match a string
^         -> match starting a string
[a-z]{3}  -> match a-z exactly 3 times
\-        -> match '-' (hyphen) character
\d{3}     -> digit exactly three times
$         -> end of the string

i         -> ignore the letter case

Is this helpful to you ? And read the below links to know more about the regular expressions

http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#op_%5E

Edited 6 Years Ago by k_manimuthu: format purpose

This question has already been answered. Start a new discussion instead.