PDA

View Full Version : really basic perl help



ShadowGandalf
25th September 2007, 12:28 PM
@tokens = ("one", "\|\|", "two");
$text = "one hundred";


for ($i=0; $i<3; $i++){
$tok = $tokens[$i];
if ($text=~m/^$tok/){
print("matched $tok with beginning of $text\n");
}
else{
print("did not match $tok with beginning of $text\n");
}
}




outputs:

matched one with beginning of one hundred
matched || with beginning of one hundred
did not match two with beginning of one hundred


second line bolded for emphasis. what am I doing wrong?

ShadowGandalf
25th September 2007, 12:46 PM
addendum: changing "\|\|" to "\174\174" yielded identical output.

addendum part 2: both versions match w/ the end of the string too.

snoop
25th September 2007, 01:06 PM
read up on regexp, $ is the end anchor of an expression; first off put $tok into parens.

Second, stylistically, most people do not use print as a function.

Third, if you're iterating @tokens anyhow, why not just do m/($tokens[$i])/.

ShadowGandalf
25th September 2007, 01:08 PM
@tokens = ("one", "\174\174", "two");
$text = "one hundred";


for ($i=0; $i<3; $i++){
$tok = $tokens[$i];
if ($text=~m/^($tok)/){
print "matched $tok with beginning of $text\n";
}
else{
print "did not match $tok with beginning of $text\n";
}
}


returns identical results.

ShadowGandalf
25th September 2007, 03:29 PM
@tokens = ("one", "X\|Y\|Z", "two");
$text = "one hundred";

for ($i=0; $i<3; $i++){
if ($text=~m/^($tokens[$i])/){
print "matched $tokens[$i] with beginning of $text\n";
}
else{
print "did not match $tokens[$i] with beginning of $text\n";
}
}
results in:


matched one with beginning of one hundred
did not match X|Y|Z with beginning of one hundred
did not match two with beginning of one hundredbut....





@tokens = ("one", "X\|Y\|", "two");
$text = "one hundred";

for ($i=0; $i<3; $i++){
if ($text=~m/^($tokens[$i])/){
print "matched $tokens[$i] with beginning of $text\n";
}
else{
print "did not match $tokens[$i] with beginning of $text\n";
}
}
results in

matched one with beginning of one hundred
matched X|Y| with beginning of one hundred
did not match two with beginning of one hundred





i thus assume that perl is reading the quote as piped alternates in a regex rather than actual bars.

ShadowGandalf
25th September 2007, 03:32 PM
solution:

put "\\|\\|" instead of "\|\|"

snoop
25th September 2007, 11:11 PM
Yeah i just kind of went for the first obvious error I saw... I didn't really bother with the rest of it (I.E. copying and pasting your code and running it).