STDIN - Getting Input without Return Characters

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • doughboy
    New Member
    • Mar 2007
    • 2

    STDIN - Getting Input without Return Characters

    I have just started learning perl. I have to write a script that will ask a persons info, ask if you want to add more records, and once it is done print all the info with a : between the fields and a blank space in between records. Here is what I have so far:

    Code:
    #!/usr/bin/perl
    open(FILE, ">>file.txt");
    while (1) {
    	print("First Name ");
    	$first = <STDIN>;
    
    	print("Last Name ");
    	$last = <STDIN>;
    
    	print FILE "$first, $last\n";
    
    	printf(Add another record? ");
    	chomp($answer = <STDIN>);
    	last if ($answer eq "n" || $answer eq "N");
    }
    close(FILE);
    The problem I have is that is saves the $first and $last on seperate lines instead of putting them on the same line with a : between them
    Last edited by miller; Mar 31 '07, 06:22 AM. Reason: Code Tag and ReFormatting
  • davidiwharper
    New Member
    • Mar 2007
    • 20

    #2
    Hi there,

    You need to chomp each input to remove the line break character entered into the script when the user presses the return/enter key after typing in each variable, just like you do later on.

    Code:
    chomp ($first= <STDIN>);
    chomp ($last = <STDIN>);
    Also, it is useful to use tab characters to visually show which bits of your code are in a function or loop (are they the right terms? still new to this):

    Code:
    my $counter = 0;
    
    while ($counter < 10) {
    
    	# do some stuff
    	$counter++;
    
    }
    Trust me, even from my very limited Perl experience this is very useful later on.

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      All you need do is chomp() the input like david has explained.

      Comment

      • doughboy
        New Member
        • Mar 2007
        • 2

        #4
        Thank you!

        Comment

        Working...