Nikhil Hegde Nikhil Hegde - 2 months ago 16
Perl Question

What is the function of this code expression?

I'm confused with the function of the regular expression:


I tried out a short perl code to understand it but I'm still confused. The code output is

my $addr2 = {[{'firstname' => 'Nikhil', 'lastname' => 'Hegde'}, {'firstname' => 'Nikhil2', 'lastname' => 'Hegde2'}]};
if($addr2 =~ /\[\]$/) {
print "If\n";
else {
print "Else\n";

I thought that
would point to whether the value is an array or not but that doesn't seem to be the case. I then thought that maybe the value has to end with an array considering that there is a
in the regular expression. So, I tried substituting:

my $addr2 = {[{'firstname' => 'Nikhil', 'lastname' => 'Hegde'}, {'firstname' => 'Nikhil2', 'lastname' => 'Hegde2'}],[]};

but that doesn't work either. The code output remains

Can anyone help me in understanding the expression
? What regular matching does it do? Thanks!


A regular expression checks matching of strings. In your case, you tried matching a hash reference. That's why your code went to the else block.

Now, the /\[\]$/. It matches any string that has a literal [] at the end of it. For example, the string my $str = "just an example []" would match this regex.