Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl exact string match

Tags:

perl

I have following Perl code to prompt user for yes/no answer. If the user enters anything else than yes/no, keep prompting. No other word is acceptable. I don't know why this code doesn't work. I tested with answer "noooooo" and I was expecting it to prompt again but it does not enter the while loop.

Can anyone help find my mistake here?

@files = A, B, C;

foreach $c (@files) {
  if (-e $c  ) { 
     print " $c already exists. Do you want to overwrite?  (yes or no): ";
     chomp ($file_yes_no = <STDIN>);

     while ($file_yes_no !~ m/yes{1}|no{1}/i )  {
         print "$c already exists. Do you want to overwrite?  (yes or no): ";
         chomp ($file_yes_no = <STDIN>);
     }

     if ($file_yes_no =~ m/yes/i ) {
         if (system ("cp -f /home/old_path/ /home/new_path/ == 0) {
             print "$c successfully copied;
         } else {
             die "Error: Copy failed, Check the message above";
         }
     }
 else { print "No files copied\n; }
like image 381
NewBie Avatar asked Dec 08 '22 17:12

NewBie


2 Answers

I would just use the string equality operator eq instead of a regex.

if( $file_yes_no eq 'yes' ) ...

If I wanted it case insensitive I'd first convert to lowercase with lc.

The problem with your regex is it will happily match any string containing the letters yes sequentially. If you wish, you can match the start and end of the string like this:

if ($file_yes_no =~ m/^yes$/i ) ...

But I personally prefer the first option.

Oh, I missed the first part... Hmmmm. Same deal, if you must use regex.

m/^(yes|no)$/i

Once again I'd be more inclined to avoid regex

like image 113
paddy Avatar answered Dec 11 '22 11:12

paddy


You should use following Perl regular expression for matching only yes or no (case insensitive):

m/^(yes|no)$/i

For yes only, use:

m/^yes$/i
like image 29
mvp Avatar answered Dec 11 '22 12:12

mvp