For those of a nervous disposition, reasurance your Perl code is actually processing something is a good thing. When writing code executed from the command line a spinner is a popular choice of providing this reassurance. When I first thought about doing this (many moons ago) I produced the following code:
my $i = 0; my @spinner = ("|\r", "/\r", "-\r", "\\\r"); while (<>) { # or any other looping structure print STDERR $spinner[$i]; $i = $i++ % @spinner; # do stuff }
After a while, and much learning, I realised I could shorten this to print STDERR $spinner[$i++ % @spinner]. I then went away happy thinking that was the best anyone could do. Until the other day. Out of the blue the following code "popped" into my head:
sub spinner { my $i; my @chars = defined @_ ? @_ : ("|\r", "/\r", "-\r", "\\\r"); return sub { "$chars[$i++ % @chars]" }; } my $spinner = spinner(); while (<>) { print STDERR $spinner->(); # do stuff }
I see this as an improvement on my last attempt for the following reasons:
1) It's more modular so I can have multiple spinners within one script, all giving different output (not sure when you'd want this mind!)
2) proves I have at least got a reasonable grip on how closures work
3) it is only fractionally slower than just printing $spinner[$i++ % @spinner]
I'd be interested in anyone elses thoughts on this code and any suggestions on how to do this differently/"better"/whatever

!unlike
"The price if ignorance, which is of course that you must learn from those with knowledge." Scorates (paraphrased)

In reply to Way of the Spinner (repost) by !unlike

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.