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 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I tried it without the quote,still doesnt match, but if i do @arr1 = grep(/4\/2/,@grepped_int);
@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)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.