if I remove square brackets around $user, the program will just output every line refusing to perform grep function.
This is because you need to force the evaluation of the $user variable. This is an example under the Perl debugger of one possible way to do it:
DB<1> @array = qw /foo foobar bar barfoo fobar foobaz /;
DB<2> x @array;
0 'foo'
1 'foobar'
2 'bar'
3 'barfoo'
4 'fobar'
5 'foobaz'
DB<3> $user = "foo";
DB<4> @a = grep /^\Q$user\E/, @array;
DB<5> print "@a";
foo foobar foobaz
DB<7> print join " ", grep !/^\Q$user\E/, @array;
bar barfoo fobar
But using square brackets does not work as expected because it is defining a character class:
DB<8> print join " ", grep !/^[$user]/, @array;
bar barfoo
DB<9> print join " ", grep /^[$user]/, @array;
foo foobar fobar foobaz
On the other hand, using ${user} instead of $user will be sufficient to get it to work properly:
DB<27> print join " ", grep /^${user}/, @array;
foo foobar foobaz
DB<28> print join " ", grep !/^${user}/, @array;
bar barfoo fobar
|