LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   question about $_ (default variable) in Perl (https://www.linuxquestions.org/questions/programming-9/question-about-%24_-default-variable-in-perl-69819/)

realos 07-03-2003 10:05 AM

question about $_ (default variable) in Perl
 
--------------
1 $! /usr/bin/perl -w
2 print "Your name please: ";
3 $_=chomp($name =<>);
4 print "hello $name! $_ \n';
---------------------------------

This code works fine in this shape but if I leave out "$_" in line 3 then there is a warning message while executing the file: "Use of uninitialized value in concatenation (.) or string at ./hello.pl line 4, <> line 1."

I thought $_ is the default variable and would store the return value of chomp function. Any idea why it is not doing that in our example?

TheLinuxDuck 07-03-2003 11:02 AM

The reason it's giving you the error is because chomp returns the number of characters removed, and in your assignment, you're telling perl to make $_ be that number, but if you remove it, the return value of chomp is discarded. $_ is only the default going IN to chomp, not out.

So, the value of $_ is undefined.

If you're wanting to assign the chomped version of $name to $_, you could say:
Code:

chomp($_ = <STDIN>);
and avoid the '$name' variable altogether, or
Code:

$_ = <STDIN>;
chomp;

to use the $_ option.

Hope this helps!

acid_kewpie 07-03-2003 11:23 AM

surely just avoiding $name altogether would actually imply nothjing more than "chomp(<>);"

i'm assuing the first line of that script is a typo.. $! instead of a normal shebang (#!)

realos 07-04-2003 06:12 AM

thank you people. Both the posts help me further. $! instead of #! _was_ actually a mistake. I did not copy and paste but had to write down the code because of not proper settings in cygwin I am using to have a Linux-console at workplace.


perldoc -f chomp does say "... it the VARIABLE is omitted, it chomps $_."

I just overlooked that.

thankx again

Salz 07-04-2003 05:09 PM

chomp <> won't work, because chomp expects a lvalue it can modify and not an operator. Neither would <>;chomp because the <> operator result is only assigned to $_ inside a while test.
$_ is the default variable, but just not for everything ;)
See man perlvar for further confusions.


All times are GMT -5. The time now is 03:10 AM.