2

I wrote the Perl module to get the user name from the user through <stdin> and print it as like below,

use strict;
use warnings;
{
    package Insert;
    sub Insert_DATA
    {
        my $User_Name;
        print "Please Enter the User Name: ";
        chomp ( $User_Name = <stdin> );
        print $User_Name , "\n";
    }
}
return 1; 

But when I executed this code, It gives the error like this,

readline() on unopened filehandle stdin at Insert_Data.pm line 26.
Use of uninitialized value $User_Name in chomp at Insert_Data.pm line 26.
Use of uninitialized value $User_Name in print at Insert_Data.pm line 27.

So please help to solve this problem.

Thanks.

Ganapathy
  • 545
  • 1
  • 6
  • 23
  • 3
    It's STDIN, not stdin. Perl is case sensitive. – ThisSuitIsBlackNot Jul 15 '16 at 12:07
  • 2
    @ThisSuitIsBlackNot: Confusingly, `stdin` and `STDIN` are synonyms. Likewise with the other `STD*` handles. Although it does warn `Unquoted string "stdout" may clash with future reserved word` if you `print stdout "xx\n"`, while correctly producing output! – Borodin Jul 15 '16 at 12:13
  • 1
    Possible duplicate of [What is the difference between and ?](http://stackoverflow.com/questions/31185416/what-is-the-difference-between-stdin-and-stdin) – ThisSuitIsBlackNot Jul 15 '16 at 12:15
  • 2
    @Borodin Ah, right, but only in main. I had forgotten about that until I found the post linked in my last comment, thanks. – ThisSuitIsBlackNot Jul 15 '16 at 12:19

1 Answers1

9

The file handle that is opened when perl starts up is STDIN or main::stdin, but you have changed packages and are trying to read from Insert::stdin, which doesn't exist

If you write <STDIN> or <main::stdin> instead then it will work as expected

But you probably shouldn't be doing top-level IO inside a package subroutine anyway, and I suggest that you accumulate all of the data in your main program and pass it as a a parameter to Insert::Insert_DATA()

I would write something like this

main.pl

use strict;
use warnings 'all';

use Insert;

print "Please Enter the User Name: ";

chomp(my $user_name = <STDIN>);

insert_data($user_name);

Insert.pm

package Insert;

use strict;
use warnings 'all';

use Exporter 'import';
our @EXPORT = 'insert_data';

sub insert_data {
    my ($user_name) = @_;

    print $user_name, "\n";
}

1;
Borodin
  • 126,100
  • 9
  • 70
  • 144