develooper Front page | perl.beginners | Postings from July 2003

RE: Is $1 ever undefined or set to null?

Thread Previous | Thread Next
From:
Bob Showalter
Date:
July 21, 2003 07:53
Subject:
RE: Is $1 ever undefined or set to null?
Message ID:
2E4528861499D41199D200A0C9B15BC001D7E9AA@FRISTX
Ed Christian wrote:
> I assumed that, $1 would be reset (either undefined or set to null)
> once I exited the scope of the while loop my regexp was called in.
> Sadly, I was mistaken. :) Below is a test example of code I wrote,
> with $1 values differing from those I expected. Do I need to
> explicitly set $1..$n to an empty string before every regexp if I'm
> to test based on the results of that regexp?
> 
> Thanks!
> - Ed
> 
> -=-=-=-=-=-
> #!/usr/bin/perl -w
> use strict;
> use warnings;
> 
> while (<DATA>) {
>         chomp;
>         /(\d+)/;
>         print "\$1: $1\n";
> }
> __DATA__
> 1
> 2
> a
> 3
> 
> 
> Expected results:
> $1: 1
> $1: 2
> $1:			# <--- was expecting an empty string
> $1: 3

You've already gotten the answer on how $1 works. But, if you want to get
undef on a failed match, you can use the match in a list context:

   my ($number) = /(\d+)/;

Now $number will contain the matched string, or undef if there was no match.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About