G'day fireblood,
As ++1nickt has pointed out,
you can't embed colour attributes in Perl formats.
That documentation extract suggests formline;
however, that has a problem with the ~~ you wanted to use.
I believe the following code achieves what you're after.
I strongly recommend writing short routines to handle the colouring:
a lot less typing in your help text and changing a colour only requires modification in one place.
I had a bit of a play around with splitting lines;
I've shown some examples with hard- and soft-hyphens;
there are probably enough ideas to see what's possible;
I'll leave you to adapt this to your needs.
[Unicode info:
"\x{1b}" eq "\N{ESCAPE}" and
"\x{ad}" eq "\N{SOFT HYPHEN}"]
#!/usr/bin/env perl
use strict;
use warnings;
use constant BASE_LINE_LENGTH => 40;
use Term::ANSIColor 'colored';
my $base_line_length = @ARGV ? $ARGV[0] : BASE_LINE_LENGTH;
my @strings = (
'A message indicating success might look'
. " some\N{SOFT HYPHEN}thing like this: "
. _good("OK: some\N{SOFT HYPHEN}thing worked.")
. ' That is, it should be green.',
'A message indicating failure might look some-thing like this: '
. _bad("Error: something didn't work.")
. ' That is, it should be yellow on red.',
);
my $off_code = "\x{1b}[0m";
my $last_code = $off_code;
for my $string (@strings) {
my $char_count = 0;
for my $substr (split /(\x{1b}\[[0-9;]+m)/, $string) {
if ($substr =~ /^\x{1b}/) {
$last_code = $substr;
}
else {
print $last_code;
CHAR: for my $char (split //, $substr) {
if ($char_count == 0) {
print $last_code;
}
if ($char_count > $base_line_length && $char =~ /[\x{a
+d} -]/) {
print '-' unless $char eq ' ';
print "$off_code\n";
$char_count = 0;
next CHAR;
}
unless ($char eq "\x{ad}") {
print $char;
++$char_count;
}
}
}
}
print "$off_code\n";
}
sub _good {
my ($string) = @_;
return colored($string, 'green');
}
sub _bad {
my ($string) = @_;
return colored($string, 'yellow on_red');
}
In the following, italicised text indicates "green";
emboldened text indicates "yellow on_red".
Example output with default base line length:
$ ./colour_format.pl
A message indicating success might look some-
thing like this: OK: something worked. That
is, it should be green.
A message indicating failure might look some-
thing like this: Error: something didn't work.
That is, it should be yellow on red.
Example output with user-supplied base line length:
$ ./colour_format.pl 32
A message indicating success might
look something like this: OK: some-
thing worked. That is, it should be
green.
A message indicating failure might
look some-thing like this: Error:
something didn't work. That is, it
should be yellow on red.
|