Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting weird error with regex '[

I am new with Perl and learning it. I write a script which provides word auto completion by tab as bash provides. If input is not in defined array, it prints predefined message and if input is in array then it run system command for the same.

It runs fine as per my assumptions but if I input only [ character, it gives errors which i can't find that why it happens.

One more thing, suppose, I type only tab without any character, it does not shows predefined commands in array.It only prompt.

Kindly guide me and if I am wrong, please correct me.

Before I am using bash shell scripts in that we have -x option to debug while run time, is there any option with Perl to do that?

my script:

 #!/usr/bin/perl

 use Term::Complete;
 use List::Util 'first';

 @cmd = qw/ls uptime clear/;
 while (defined @cmd) {

     $in = Complete('prompt', @cmd);
     if (first { /$in/ } @cmd) {

         system($in);
     }
     elsif ($in eq 'exit') {

         `kill -9 $$`;
     }
     else {

         print "Use these commands: ls uptime clear";
    }
}

Error , if i enter [ :

perl tab1.pl 
prompt uptime
12:02:31 up  3:29,  2 users,  load average: 0.00, 0.00, 0.00
prompt [
Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE / at tab1.pl line 8.

BR Ben

like image 820
Ben Avatar asked Dec 07 '25 04:12

Ben


2 Answers

[ is a special character in regex, you have to escape it.

If you read the input from user, and want to search as is, you can use \Q and \E:

/\Q$in\E/
like image 88
J-16 SDiZ Avatar answered Dec 08 '25 17:12

J-16 SDiZ


if you like to insert [ as literal you should escape it with backslash (\)

Otherwise it has a special meaning in regular expressions

like image 39
Serge Avatar answered Dec 08 '25 17:12

Serge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!