How to find all occurrences of a string in another string using Perl

Rating 3.00 out of 5

How to find all occurrences of a string in another string using Perl?

#!/usr/bin/perl
use strict;
use warnings;

my $string = ‘needle in the haystack. needle again. needle’;
my $find_me = ‘needle’;
my $offset = 0;
my $result = index($string, $find_me, $offset);

while ($result != -1) {
print “Found $find_me at $result\n”;
$offset = $result + . . . → Read More: How to find all occurrences of a string in another string using Perl

Greedy Search in Perl Regular Expressions

Rating 2.33 out of 5

You might have come across the problem of .* capturing all the pattern it matches in the string, while you wanted only a part of it. E.g.,

$var = ‘some_url?id=1&number=2&name=Peter&address=someaddress’;

In the above string if you only want to capture the value of “id” (i.e. 1) and you use this regex

$var =~ /\?(.*)=(.*)\&/ ;

it will not work as . . . → Read More: Greedy Search in Perl Regular Expressions

How to know if document exists on a URL in perl

Rating 3.00 out of 5

Pinging a server doesn’t not actually tell if the web server is up and available or not.  To check if a server is available and responding or a document exists on a URL, use this,

use LWP::Simple;
$URL=’http://www.expertsguide.info/’;
if (head($URL))
{
print ‘$URL exists’ ;
}
else
{
   print ‘URL does not contain anything’;
}

head() function . . . → Read More: How to know if document exists on a URL in perl

How to get elements from one array but not in another array

Rating 3.00 out of 5

How to get elements from one array but not in another array.

Or, in other words, how to get elements from one array minus elements from another array.

The task can be simplified and made efficient (less loops and less iterations) by creating a hash (associative array) from one array elements and then matching . . . → Read More: How to get elements from one array but not in another array

Alter Regular Expression Match Position in Perl

Rating 4.00 out of 5

How to alter the regular expression match position?

The perl function pos() retrieves or modifies the position where the next match attempt is going to begin. The beginning of a string (first character) has a position zero. This position can be modified by using the function as the left side of an assignment, . . . → Read More: Alter Regular Expression Match Position in Perl