Why can't I use if($l =~ $ARGV[0]) but I can use if($l =~ /$ARGV[0]/g?

first case
$ perl script.pl '/^[\w]/g'
second case
$ perl script.pl '^[\w]'

Strings and regexes are different primitive types in perl, and all variables placed in the @ARGV array are simply strings given to the program by the kernel at startup; $ARGV[0] is a scalar string, and not a regex.

When you do if($l =~ $ARGV[0]) and $ARGV[0] is '/^[\w]/g' this is equivalent to if($l =~ '/^[\w]/g') instead of if($l =~ /^[\w]/g). In the former case the slashes are simply characters in a string while in the later they are a part of the Perl syntax that delimits a regular expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.