Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

arrays again 3

Status
Not open for further replies.

ailse

Programmer
Jan 20, 2004
79
GB
Is it possible to search arrays as you would a string? my problem is that I need to look in a string for a particular pattern, but after matching i need to be able to state the position in the string it is located at, hence the need for an array...

any hints would be great :)
 
You can make use of the [tt]@-[/tt] array, which contains locations of pattern matches.

For example:
[tt]my $str = "this is a test";
$str =~ /\s+is/;

print $-[0];[/tt]

prints 4 (location starts with 0 as the first character), the location of the first whitespace character from the pattern.

[tt]$-[0][/tt] is the position of the overall match.
[tt]$-[1][/tt] would be the position of the first submatch (if we had groupings in our regexp)
etc.

Hope this answers your question.
 
I copy this from man perlretut, holp it will help.

$x = "Mmm...donut, thought Homer";
$x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
foreach $expr (1..$#-) {
print "Match $expr: '${$expr}' at position ($-[$expr],$+[$expr])\n";
}

prints

Match 1: 'Mmm' at position (0,3)
Match 2: 'donut' at position (6,11)
 
nice answer yang yang - a star for that!

but what the heck is that face in the foreach???


Kind Regards
Duncan
 
It's supposed to be $ # - (without spaces.) The size of the [tt]@-[/tt] array.
 
you can use index function:

$pos = index ($string, $lookfor, $startPos);

when used in loop you can all positions.

$pos=-1;
$startPos=0;
while(($pos = index($string, $lookfor, $startPos))>-1){
print "Found at $pos\n";
$startPos=++$pos;
}
 
Cheers for all these tips guys - one problem tho, when I try to run the code give by yangyang I keep getting the same errors:

"use of $# deprecated"
"use of uninitialized value in foreach loop entry"

am I missing something obvious?


Sirisha :)
 
You can change it to:
[tt]foreach my $expr (1 .. (scalar(@-) - 1)) {[/tt]

[tt]$#array[/tt] returns the index of the last element of the array [tt]@array[/tt]. [tt]scalar(@array)[/tt] returns the number of elements of [tt]@array[/tt]. The latter being one higher than the former.

I didn't realize that [tt]$#[/tt] was deprecated. Must be in perl 5.8.

Not sure about the use of uninitialized variable. It might be because of the [tt]$#[/tt] thing.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top