| 1 | #!/usr/bin/perl -c | ||
| 2 | |||
| 3 | package MooseX::Types::CanonOpenModeStr; | ||
| 4 | |||
| 5 | =head1 NAME | ||
| 6 | |||
| 7 | MooseX::Types::CanonOpenModeStr - Type for canonical open mode string | ||
| 8 | |||
| 9 | =head1 SYNOPSIS | ||
| 10 | |||
| 11 | package My::Class; | ||
| 12 | use Moose; | ||
| 13 | use MooseX::Types::CanonOpenModeStr; | ||
| 14 | has file => ( isa => 'Str' ); | ||
| 15 | has mode => ( isa => 'CanonOpenModeStr', coerce => 1 ); | ||
| 16 | |||
| 17 | package main; | ||
| 18 | # This will be coerced | ||
| 19 | my $fin = My::Class->new( file => '/etc/passwd', mode => 'r' ); | ||
| 20 | # This is native mode | ||
| 21 | my $fout = My::Class->new( file => '/tmp/pwdnew', mode => '>' ); | ||
| 22 | |||
| 23 | =head1 DESCRIPTION | ||
| 24 | |||
| 25 | This module provides Moose type which represents Perl-style canonical open | ||
| 26 | mode string (i.e. "+>"). | ||
| 27 | |||
| 28 | =cut | ||
| 29 | |||
| 30 | |||
| 31 | use strict; | ||
| 32 | use warnings; | ||
| 33 | |||
| 34 | our $VERSION = '0.1004'; | ||
| 35 | |||
| 36 | use Moose::Util::TypeConstraints; | ||
| 37 | |||
| 38 | |||
| 39 | subtype CanonOpenModeStr => ( | ||
| 40 | as 'Str', | ||
| 41 | where { /^\+?(<|>>?)$/ }, | ||
| 42 | optimize_as { | ||
| 43 | defined $_[0] && !ref($_[0]) | ||
| 44 | && $_[0] =~ /^\+?(<|>>?)$/ | ||
| 45 | }, | ||
| 46 | ); | ||
| 47 | |||
| 48 | coerce CanonOpenModeStr => ( | ||
| 49 | from OpenModeStr => | ||
| 50 | via { | ||
| 51 | local $_ = $_; | ||
| 52 | s/^r(\+?)$/$1</; | ||
| 53 | s/^w(\+?)$/$1>/; | ||
| 54 | s/^a(\+?)$/$1>>/; | ||
| 55 | $_; | ||
| 56 | } | ||
| 57 | ); | ||
| 58 | |||
| 59 | |||
| 60 | 1; | ||
| 61 | |||
| 62 | |||
| 63 | __END__ |