On 21/02/2012 19:47, Vyacheslav wrote:
Hello.

I'm new in perl and have many questions.

This my first programm.

#!/usr/bin/perl

use strict;
use warnings;

my $number = 0;
my $_ = 0;
print "Enter number:";
chomp($number = <>);
if ( $number = /[0-9]/) {
print "you number $number\n"
}

./firsh.pl
Enter number: 23
I thought, what print was
"you number 23"

but result was
"you number 1"
How i can return 23, if pattern match.

Hello Vyacheslav and welcome to Perl.

The expression

  $number = /[0-9]/

Doesn't do what you think. A single equals sign always *assigns*
something, so you are altering the contents of $number (to 1) instead of
testing it.

The regex /[0-9]/ checks whether the target string contains a single
numeric character. If you want to make sure that $number is a string of
digits then you should write

  $number =~ /^[0-9]+$/

Note the =~ operator, which applies a regular expression to a scalar
value, and returns true or false according to whether or not the string
matched.

Also, you *mustn't* declare $_ as it is a built-in Perl variable that
will always be available and is handled by Perl itself. You can assign
to it, but mostly you will be reading or testing its value.

If you change your program to the code below you should see what you expect.

HTH

Rob


use strict;
use warnings;

my $number;
print "Enter number: ";
chomp($number = <>);

if ( $number =~ /^[0-9]+$/ ) {
  print "Your number: $number\n"
}

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to