Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Letter by letter

by DaveMonk (Acolyte)
on Apr 20, 2012 at 18:16 UTC ( #966227=perlquestion: print w/ replies, xml ) Need Help??
DaveMonk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there, I was wondering if there is a more efficient way of printing a string out letter by letter. At the moment I am doing it like:
for ($i=0; $i=1; $i++) { print "s"; sleep 1; [... etc ...] }
But it looks and feels stupid. Is there a better way?

Comment on Letter by letter
Download Code
Re: Letter by letter
by Riales (Hermit) on Apr 20, 2012 at 18:22 UTC

    Why the sleep after each print? Are you perhaps suffering from buffering?

    If not, my initial thought when I think about printing a string letter by letter would be:

    $| = 1; print $_ foreach (split '', $string);

    Edit: I took a second look at the code you provided. I'm really not sure I understand what you're trying to do now. The second bit of the for loop is supposed to be a test that tells the loop when to stop, but since you're just assigning to $i, I'm pretty sure that loop will run forever.

      Hmm... it prints out the string directly. I want it to instead of print "string", to make it so it has 1 second intervals between each character it's printing... But im going to read the article you linked me.

        Ah, in that case, I think you were mostly on the right track except with the buffering thing and the end case for the for loop.

        $| = 1; foreach my $letter (split '', $string) { print $letter; sleep 1; }
Re: Letter by letter
by JavaFan (Canon) on Apr 20, 2012 at 19:01 UTC
    That indeeds looks stupid. The loop will never terminate, as the middle expression, $i=1 will always be true. It's probably not your intention, but then, you aren't saying what you want to do.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://966227]
Approved by kennethk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2014-07-25 02:30 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (167 votes), past polls