#!/usr/bin/perl -w use strict; my $str = "is the best way to match which of two strings occurs first in a text"; my $first = "two"; my $second = "match"; $str =~ m/($first|$second)/g; print $1 if($1); # $1 will hold first matched value