Posts

Showing posts with the label Perl

Check Whether A String Contains A Substring

Answer : To find out if a string contains substring you can use the index function: if (index($str, $substr) != -1) { print "$str contains $substr\n"; } It will return the position of the first occurrence of $substr in $str , or -1 if the substring is not found. Another possibility is to use regular expressions which is what Perl is famous for: if ($mystring =~ /s1\.domain\.com/) { print qq("$mystring" contains "s1.domain.com"\n); } The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators. my $substring = "s1.domain.com"; if ($mystring =~ /\Q$substring\E/) { print qq("$mystring" contains "$substring"\n); } Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0 . Thus, this is an error: my $substring = "s1.domain....

Can Anybody Please Explain (my $self = Shift) In Perl

Answer : First off, a subroutine isn't passed the @ARGV array. Rather all the parameters passed to a subroutine are flattened into a single list represented by @_ inside the subroutine. The @ARGV array is available at the top-level of your script, containing the command line arguments passed to you script. Now, in Perl, when you call a method on an object, the object is implicitly passed as a parameter to the method. If you ignore inheritance, $obj->doCoolStuff($a, $b); is equivalent to doCoolStuff($obj, $a, $b); Which means the contents of @_ in the method doCoolStuff would be: @_ = ($obj, $a, $b); Now, the shift builtin function, without any parameters, shifts an element out of the default array variable @_ . In this case, that would be $obj . So when you do $self = shift , you are effectively saying $self = $obj . I also hope this explains how to pass other parameters to a method via the -> notation. Continuing the example I've stated a...