1

I have the following lines of code in a perl file:

@arr1 = grep(/"$subslots_det[0]"/,@grepped_int);

for ur reference the @grepped_int array's dump looks like this:

$VAR1 = [
'GigabitEthernet4/2/1   unassigned      YES NVRAM  administratively down down    ',
'GigabitEthernet7/1     unassigned      YES NVRAM  administratively down down    ',
'GigabitEthernet7/2     unassigned      YES NVRAM  administratively down down    ',
        ]

Here lets assume, $subslots_det[0] = "4/2";

So the grep statement should match:

GigabitEthernet4/2/1   unassigned      YES NVRAM  administratively down down    ',

Right now it doesnt not do that,iam suspecting it is because of the forward slash in 4/2. Is there a way i can escape the forward slash in the following command:

@arr1 = grep(/"$subslots_det[0]"/,@grepped_int);

1 Answers1

5

It's because of double quotes.

@arr1 = grep(/$subslots_det[0]/, @grepped_int);

Regular expression itself serves as quoting, and therefore the quotes around $subslots_det[0] simply serve as literal quote characters, so you're trying to match "4/2" instead of 4/2 .

Ex:

>perl -e '@s=("a/1","b/2"); @res=grep(/$s[0]/,("aa/1","bb/2")); print @res."\n"'
1

>perl -e '@s=("a/1","b/2"); @res=grep(/"$s[0]"/,("aa/1","bb/2")); print @res."\n"'
0

Also, if you worry about escaping "/" character (which you should not unless it's used as a literal inside the regex itself), you can always change the regex delimiter from "/" to "#" or any other character:

@arr1 = grep(m#$subslots_det[0]#, @grepped_int);
@arr1 = grep(m!$subslots_det[0]!, @grepped_int);
Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327
  • I tried it without the quote,still doesnt match, but if i do @arr1 = grep(/4\/2/,@grepped_int); – user3094070 Feb 11 '14 at 05:59
  • @user3094070 - the escaping of the "/" is ONLY needed when it's a literal character. You can easily test that by changing regex character from "/" to "#" so you don't need to care about escaping it: `@arr1 = grep(m#$s[0]#,@grepped_int)` – DVK Feb 11 '14 at 06:05
  • sorry my mistake:) i had defined the criteria for match differently,thats y it dint match,now it works perfectly,thanks a lot,answer accepted. – user3094070 Feb 11 '14 at 06:10