Hi all again,
Some time ago I came back to Perl world. Today I'd like to discuss some stuff. It has to do with output formatting, generation of the indentation literally. I tried to implement the module the simple as much as possible. of course, I know there is a lot of modules with the same functionality (for example,
Text::Indent,
Print::Indented or
String::Indent). Most probably, those modules more powerful and more flexible than mine. But I needed:
-- simplicity
-- easiness
-- immediate effect
Completing this module, I guess achieved the main goals. It is quite easy in use, clear and effective. It doesn't support buffering or formatting to a string and doesn't support printing to other streams.
Example of usage:
# use 4 spaces indents and automatic line ending
use indent indent_size => 4, indent_eol => 1;
indent::new;
indent::printf "Hello, world!";
indent::new;
indent::printf "Hello, world!";
indent::back;
indent::printf "Hello, world!";
indent::back;
The resulting output is as follows:
Hello, world!
Hello, world!
Hello, world!
The full source of the module is below:
package indent;
use strict;
use warnings;
our $INDENT = " " x 4;
our $EOL = $\;
sub import {
shift;
goto &config;
}
sub config {
my %opts = @_;
if ( $opts{indent_tab} ) {
$INDENT = "\t";
} elsif (
defined $opts{indent_size}
&& $opts{indent_size} =~ /^\d+$/
) {
$INDENT = " " x $opts{indent_size};
}
if ( defined $opts{indent_eol} ) {
$EOL = $opts{indent_eol} ? "\n" : $\;
}
}
my @indent = ( "" );
sub reset {
@indent = $indent[0];
}
sub current {
$indent[-1];
}
sub new {
push @indent, current . $INDENT;
}
sub back {
pop @indent if @indent > 1;
}
sub print {
local $\ = $EOL;
CORE::print current, @_;
}
sub vprint {
local $\ = $EOL;
CORE::print current, $_ for ( @_ );
}
sub printf {
indent::print sprintf(( shift || "" ), @_);
}
1;
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.