strange behavior of ??

N

Nathan

Hi,

The definition of the m?? operator says that it only matches once
between calls to reset. When I ran the following program I confirmed
this behavior:

#!/usr/bin/perl
$_ = "Bilbo Baggins";
for($i=0;$i<5;$i++) {
$a = ?Bilbo?;
}

That is, $a was set to 1 initially and then '' on every pass through the
loop afterward. However, $a does not seem to be set to 1 at all in this
program:

#!/usr/bin/perl
$_ = "Bilbo Baggins";
for (0..4) {
$a = ?Bilbo?;
}

Initially $a is not defined and then it stays '' on each loop pass. I am
running perl v5.8.8 on linux. My understanding is these two programs are
supposed to be equivalent, so why am I observing different behavior with
the debugger in the second one?

-Nathan
 
Z

Zak B. Elep

Nathan said:
#!/usr/bin/perl
$_ = "Bilbo Baggins";
for (0..4) {
$a = ?Bilbo?;
}

Initially $a is not defined and then it stays '' on each loop pass. I am
running perl v5.8.8 on linux. My understanding is these two programs are
supposed to be equivalent, so why am I observing different behavior with
the debugger in the second one?

It is because you're aliasing the $_ to the elements of 0..4 in the
for() loop, which not what you expect when you assigned a string to it.
You should then use another scalar in the for() to alias the elements
to, for instance:

,----
| $_ = "Bilbo Baggins";
| for my $count ( 0 .. 4 ) {
| $a = ?Bilbo?;
| print "At $count, \$a is $a\n";
| }
`----
 
Z

Zak B. Elep

Nathan said:
Thanks very much, that was very confusing to me. Perl does so many
things automatically and behind the scenes I can't imagine coding in it
*without* the debugger...

`perl -de 0' provides a nice basic interactive perl. Devel::REPL[1] is
also a fine alternative for quickly testing out/debugging code. :)


Footnotes:
[1] http://search.cpan.org/perldoc?Devel::REPL
 
E

Eric Pozharski

Nathan said:
Thanks very much, that was very confusing to me. Perl does so many
things automatically and behind the scenes I can't imagine coding in
it *without* the debugger...

Add C<use strict> and C<use warnings>. Or better B<carefully> read
documentation.
 
D

Dr.Ruud

Nathan schreef:
#!/usr/bin/perl
$_ = "Bilbo Baggins";
for (0..4) {
$a = ?Bilbo?;
}

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

my $s = "Bilbo Baggins";

for ( 0 .. 4 ) {
print "$_ ",
$s =~ m?Bilbo?
? "1"
: "-",
;
}
__END__

0 1
1 -
2 -
3 -
4 -


I (almost) never directly assign to $_ in my code, there is just no
need.

Always use both strict and warnings. Better not use $a or $b.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top