Acme-Tie-Formatted

 view release on metacpan or  search on metacpan

lib/Acme/Tie/Formatted.pm  view on Meta::CPAN

package Acme::Tie::Formatted;
use strict;
use warnings;
use Carp;

our $VERSION = '0.06';

my $first_char = qr/[_a-zA-Z]/;
my $next_char  = qr/[_a-zA-Z0-9]/;
my $ok_name    = qr/^$first_char($next_char)*$/;

our %format;

sub import {
  $DB::single=1;
  my ($class, $arg) = @_;
  my $hash_name = "format";

  if (defined $arg and $arg =~ /$ok_name/) {
    $hash_name = $arg;
  }

  {
    no strict 'refs';
    *{"main::$hash_name"} = \%format;
  }

  # Connect the magic to the hash.
  tie %format, 'Acme::Tie::Formatted';
}


sub TIEHASH {
  my $class = shift;

  # Someplace to hang our hat.
  bless \my($self), $class;
}

sub FETCH {
  my ($self, $key) = @_;
  return '' unless $key;

  my @args = split $;, $key, -1;

  # Return a null string if nothing was passed in.
  return '' unless @args;

  my $format = pop @args;

  # Return a null string if there were no arguments
  # to be formatted.
  return '' unless @args;

  # Format arguments and return.
  local $_;
  return join($", map { sprintf($format, $_) } @args);
}

# Stolen directly from Tie::Comma.
# Invalidate all other hash access.
use subs qw(
 STORE    EXISTS    CLEAR    FIRSTKEY    NEXTKEY  );
*STORE = *EXISTS = *CLEAR = *FIRSTKEY = *NEXTKEY =
  sub {
    croak "You can only use %format by accessing it";
  };


1; # Magic true value required at end of module

__END__

=head1 NAME

Acme::Tie::Formatted - embed sprintf() formatting in regular print()


=head1 VERSION

This document describes Acme::Tie::Formatted version 0.03


=head1 SYNOPSIS

    use Acme::Tie::Formatted;
    print "The value is $format{$number, "%3d"} ",
          "(or $format{$number, "%04x"} in hex)\n";

    print "some numbers: $format{ 12, 492, 1, 8753, "%04d"}\n";

=head1 DESCRIPTION

This module creates a global read-only hash, C<%format>, for formatting
data items with standard C<sprintf> format specifications. Since it's a
hash, you can interpolate it into strings as well as use it standalone.

The hash should be "accessed" with two or more "keys". The last key
is interpreted as a C<sprintf> format for each data item specified in the
preceeding arguments. This allows you to format multiple items at once
using the same format for each.

=head2 Alternate name

If you prefer, you can specify a different name for the magical
formatting hash by supplying it as as argument when C<use>ing the
module:

  use Acme::Tie::Formatted qw(z);

This makes C<%z> the magic hash instead.

  print "This is hex: $z{255, "%04x"}\n";

C<Acme::Tie::Formatted> currently supports only one format in the final
argument; this may change if there is demand for it.

=head1 DIAGNOSTICS

=over



( run in 2.328 seconds using v1.01-cache-2.11-cpan-140bd7fdf52 )