Home: Perl Programming Help: Advanced:
How do I search for a set of characters within a variable?



bobjones
Deleted

Nov 24, 2000, 6:48 AM


Views: 1824
How do I search for a set of characters within a variable?

If I had a variable $bob = "to the end"
How do I search for "end", for example, in the variable? Lets say to display $bob if "end" is found


perlplexer
Deleted

Nov 24, 2000, 7:13 AM


Views: 1824
Re: How do I search for a set of characters within a variable?

1) Using Regular Expressions (perldoc perlre)

$foo = 'foo';
$bar = "foo bar bear";
print $bar if $bar =~ /$foo/;

Looks for 'foo' in $bar. Prints $bar if
'foo' is found.

2) Using index() (perldoc -f index)

$foo = 'foo';
$bar = "foo bar bear";
print $bar if index($bar, $foo)+1;

Looks for 'foo' in $bar. Prints $bar if
'foo' is found.

-------------------------
NOTE: method 2 is faster but less flexible if you want to do more complex searches.