user2524169
user2524169

Reputation: 267

Print Line By Line

I've been trying to work on a lyrical bot for my server, but before I started to work on it, I wanted to give it a test so I came up with this script using the Lyrics::Fetcher module.

use strict;
use warnings;

use Lyrics::Fetcher;

my ($artist, $song) = ('Coldplay', 'Adventures Of A Lifetime');

my $lyrics = Lyrics::Fetcher->fetch($artist, $song, [qw(LyricWiki AstraWeb)]);

my @lines = split("\n\r", $lyrics);

foreach my $line (@lines) {
        sleep(10);
        print $line;
}

This script works fine, it grabs the lyrics and prints it out in a whole(which is not what I'm looking for).

I was hoping to achieve a line by line print of the lyrics every 10 seconds. Help please?

Upvotes: 3

Views: 334

Answers (2)

Borodin
Borodin

Reputation: 126722

You will need to enable autoflush, otherwise the lines will just be buffered and printed when the buffer is full or when the program terminates

STDOUT->autoflush;

You can use the regex generic newline pattern \R to split on any line ending, whether your data contains CR, LF, or CR LF. This feature is available only in Perl v5.10 or better

my @lines = split /\R/, $lyrics;

And you will need to print a newline after each line of lyrics, because the split will have removed them

print $line, "\n";

Upvotes: 3

Grant McLean
Grant McLean

Reputation: 6998

Your call to split looks suspicious. In particular the regex "\n\r". Note, the first argument to split is always interpreted as a regex regardless of whether you supply a quoted string.

On Unix systems the line ending is typically "\n". On DOS/Windows it's "\r\n" (the reverse of what you have). On ancient Macs it was "\r". To match all thre you could do:

my @lines = split(/\r\n|\n|\r/, $lyrics);

Upvotes: 5

Related Questions