Frage

I want to read a string from a the first line in a file, then repeat it n repetitions in the console, where n is specified as the second line in the file.

Simple I think?

#!/usr/bin/perl
open(INPUT, "input.txt");
chomp($text = <INPUT>);
chomp($repetitions = <INPUT>);
print $text x $repetitions;

Where input.txt is as follows

Hello
3

I expected the output to be

HelloHelloHello

But words are new line separated despite that chomp is used.

Hello
Hello
Hello

You may try it on the following Perl fiddle CompileOnline

The strange thing is that if the code is as follows:

#!/usr/bin/perl
open(INPUT, "input.txt");
chomp($text = <INPUT>);
print $text x 3;

It will work fine and displays

HelloHelloHello

Am I misunderstanding something, or is it a problem with the online compiler?

War es hilfreich?

Lösung

You have issues with line endings; chomp removes trailing char/string of $/ from $text and that can vary depending on platform. You can however choose to remove from string any trailing white space using regex,

open(my $INPUT, "<", "input.txt");
my $text = <$INPUT>;
my $repetitions = <$INPUT>;

s/\s+\z// for $text, $repetitions;
print $text x $repetitions;

I'm using an online Perl editor/compiler as mentioned in the initial post http://compileonline.com/execute_perl_online.php

The reason for your output is that string Hello\rHello\rHello\r is differently interpreted in html (\r like line break), while in console \r returns cursor to the beginning of the current line.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top