Is there any way I can access a part of a string in Perl?
Look at:
http://perldoc.perl.org/functions/substr.html
my $A = 0;
my @results = grep {/$IP/ ? $A=6 : $A-- > 0} <IN>;
I have understood the ?: operator from our previous discussion. Please let me know if I am right,
1. if grep is successful, A is set to 6 , print the current line
2. if grep is not successful, decremet A , print the current line
This would print 6 lines after the line with the grep argument,
If the grep is not successful right in the start, A =1 and decrementing it would push it to 0, >0 condition not satisfied, so dont print current line.
Is that the right interpretation of the code?
Close, but not quite verbally correct:
1. if the pattern /$IP/ matches, then $A=6 is used as the condition for grep. The statement $A=6 sets $A to 6, and then returns true (6), so the line is added to @results.
2. if the pattern /$IP/ doesn't match, then $A-- > 0 is used as the condition for grep. The statement $A-- > 0 is treated as $A > 0 by grep, and then a decrement is done to $A after the value check. So if the pre decrement value of $A is greater than 0, that the line is also added to @results.
Again, it is a lot harder to write out what is happening in words, than it is to just write it out in perl. But thank you for trying. It sounds like you have a good grasp of what was going on there. The hardest part to understand being the operator precedence.
Warning more advanced, probably unneeded knowledge to follow
Your use of /$IP/ is probably not completely correct. I'm assuming that $IP is an ip address. So if $IP='192.168.1.1', the pattern would be /192.168.1.1/. You might notice there is a problem with the above regular expression, namely the dots (.). That catches a lot more ip address than you probably intend, like 192.168.141.255. Instead, you want the dots to be treated as literals, and there is an easy shortcut for you to do this.
Just use /\Q$IP\E/ as your pattern.
Try printing out "\Q$IP\E" to see what those escape sequences actually do. They come in handle in regular expression all the time when working with literals. You can read more about them at:
http://perldoc.perl.org/functions/quotemeta.html http://perldoc.perl.org/perlretut.ht...racter-classes