3
######################################
4
# The real code is in perl5i::2 #
6
######################################
9
use perl5i::VERSION; our $VERSION = perl5i::VERSION->VERSION;
11
my $Latest = perl5i::VERSION->latest;
16
perl5i will break compatibility in the future, you can't just "use perl5i".
18
Instead, "use $Latest" which will guarantee compatibility with all
19
features supplied in that major version.
21
Type "perldoc perl5i" for details in the section "Using perl5i".
33
perl5i - Fix as much of Perl 5 as possible in one pragma
41
$ perl5i your_script.pl
45
Perl 5 has a lot of warts. There's a lot of individual modules and
46
techniques out there to fix those warts. perl5i aims to pull the best
47
of them together into one module so you can turn them on all at once.
49
This includes adding features, changing existing core functions and
50
changing defaults. It will likely not be 100% backwards compatible
51
with Perl 5, though it will be 99%, perl5i will try to have a lexical
54
Please add to this imaginary world and help make it real, either by
55
telling me what Perl looks like in your imagination
56
(F<http://github.com/schwern/perl5i/issues>) or make a fork (forking on
57
github is like a branch you control) and implement it yourself.
62
Because perl5i I<plans> to be incompatible in the future, you do not
63
simply C<use perl5i>. You must declare which major version of perl5i
64
you are using. You do this like so:
66
# Use perl5i major version 2
69
Thus the code you write with, for example, C<perl5i::2> will always
70
remain compatible even as perl5i moves on.
72
If you want to be daring, you can C<use perl5i::latest> to get the
75
If you want your module to depend on perl5i, you should depend on the
76
versioned class. For example, depend on C<perl5i::2> and not
79
See L</VERSIONING> for more information about perl5i's versioning
85
perl5i enables each of these modules and adds/changes these functions.
86
We'll provide a brief description here, but you should look at each of
87
their documentation for full details.
90
=head2 The Meta Object
92
Every object (and everything is an object) now has a meta object
93
associated with it. Using the meta object you can ask things about
94
the object which were previously over complicated. For example...
97
my $class = $obj->mo->class;
100
my @isa = $obj->mo->isa;
102
# the complete inheritance hierarchy
103
my @complete_isa = $obj->mo->linear_isa;
105
# the reference type of the object
106
my $reftype = $obj->mo->reftype;
108
A meta object is used to avoid polluting the global method space.
109
C<mo> was chosen to avoid clashing with Moose's meta object.
111
See L<perl5i::Meta> for complete details.
114
=head2 Subroutine and Method Signatures
116
perl5i makes it easier to declare what parameters a subroutine takes.
119
say "Hello, $place!\n";
123
return $self->{$key};
126
method new($class: %args) {
127
return bless \%args, $class;
130
C<func> and C<method> define subroutines as C<sub> does, with some
133
The signature syntax is currently very simple. The content will be
134
assigned from @_. This:
136
func add($this, $that) {
137
return $this + $that;
143
my($this, $that) = @_;
144
return $this + $that;
147
C<method> defines a method. This is the same as a subroutine, but the
148
first argument, the I<invocant>, will be removed and made into
152
return $self->{$key};
158
return $self->{$key};
161
Methods have a special bit of syntax. If the first item in the
162
siganture is C<$var:> it will change the variable used to store the
165
method new($class: %args) {
166
return bless $class, \%args;
174
return bless $class, \%args;
177
Anonymous functions and methods work, too.
179
my $code = func($message) { say $message };
183
@_ will not be modified except by removing the invocant
185
Future versions of perl5i will add to the signature syntax and
186
capabilities. Planned expansions include:
189
Signature documentation
194
Anonymous method and function declaration
195
Variable method and function names
197
Traditional prototypes
199
See L<http://github.com/schwern/perl5i/issues/labels/syntax#issue/19> for
200
more details about future expansions.
202
The equivalencies above should only be taken for illustrative
203
purposes, they are not guaranteed to be literally equivalent.
205
Note that while all parameters are optional by default, the number of
206
parameters will eventually be enforced. For example, right now this
209
func add($this, $that) { return $this + $that }
211
say add(1,2,3); # says 3
213
The extra argument is ignored. In future versions of perl5i this will
217
=head3 Signature Introspection
219
The signature of a subroutine defined with C<func> or C<method> can be
220
queried by calling the C<signature> method on the code reference.
222
func hello($greeting, $place) { say "$greeting, $place" }
225
say $code->signature->num_positional_params; # prints 2
227
Functions defined with C<sub> will not have a signature.
229
See L<perl5i::Signature> for more details.
234
L<autobox> allows methods to be defined for and called on most
235
unblessed variables. This means you can call methods on ordinary
236
strings, lists and hashes! It also means perl5i can add a lot of
237
functionality without polluting the global namespace.
239
L<autobox::Core> wraps a lot of Perl's built in functions so they can
240
be called as methods on unblessed variables. C<< @a->pop >> for example.
244
$scalar_reference->alias( @identifiers );
245
@alias->alias( @identifiers );
246
%hash->alias( @identifiers );
247
(\&code)->alias( @identifiers );
249
Aliases a variable to a new global name.
251
my $code = sub { 42 };
252
$code->alias( "foo" );
253
say foo(); # prints 42
255
It will work on everything except scalar references.
258
%other_hash->alias( "stuff" ); # %stuff now aliased to %other_hash
260
It is not a copy, changes to one will change the other.
262
my %things = (foo => 23);
264
%things->alias( "stuff" ); # alias %things to %stuff
265
$stuff{foo} = 42; # change %stuff
266
say $things{foo}; # and it will show up in %things
268
Multiple @identifiers will be joined with '::' and used as the fully
269
qualified name for the alias.
271
my $class = "Some::Class";
273
sub { 99 }->alias( $class, $name );
274
say Some::Class->foo; # prints 99
276
If there is just one @identifier and it has no "::" in it, the current
277
caller will be prepended. C<< $thing->alias("name") >> is shorthand for
278
C<< $thing->alias(CLASS, "name") >>
280
Due to limitations in autobox, non-reference scalars cannot be
281
aliased. Alias a scalar ref instead.
284
$thing->alias("foo"); # error
287
$thing->alias("foo"); # $foo is now aliased to $thing
289
This is basically a nicer way to say:
292
*{$package . '::'. $name} = $reference;
295
=head2 Scalar Autoboxing
297
perl5i adds some methods to scalars of its own.
301
my $centered_string = $string->center($length);
302
my $centered_string = $string->center($length, $character);
304
Centers $string between $character. $centered_string will be of
307
C<$character> defaults to " ".
309
say "Hello"->center(10); # " Hello ";
310
say "Hello"->center(10, '-'); # "---Hello--";
312
C<center()> will never truncate C<$string>. If $length is less
313
than C<< $string->length >> it will just return C<$string>.
315
say "Hello"->center(4); # "Hello";
319
my $rounded_number = $number->round;
321
Round to the nearest integer.
327
my $new_number = $number->round_up;
329
Rounds the $number towards infinity.
332
(-2.45)->round_up; # -2
334
ceil() is a synonym for round_up().
341
my $new_number = $number->round_down;
343
Rounds the $number towards negative infinity.
345
2.45->round_down; # 2
346
(-2.45)->round_down; # -3
348
floor() is a synonyn for round_down().
353
$is_a_number = $thing->is_number;
355
Returns true if $thing is a number understood by Perl.
357
12.34->is_number; # true
358
"12.34"->is_number; # also true
359
"eleven"->is_number; # false
363
$is_positive = $thing->is_positive;
365
Returns true if $thing is a positive number.
371
$is_negative = $thing->is_negative;
373
Returns true if $thing is a negative number.
379
$is_even = $thing->is_even;
381
Returns true if $thing is an even integer.
385
$is_odd = $thing->is_odd;
387
Returns true if $thing is an odd integer.
391
$is_an_integer = $thing->is_integer;
393
Returns true if $thing is an integer.
395
12->is_integer; # true
396
12.34->is_integer; # false
397
"eleven"->is_integer; # false
401
A synonym for is_integer
405
$is_a_decimal_number = $thing->is_decimal;
407
Returns true if $thing is a decimal number.
409
12->is_decimal; # false
410
12.34->is_decimal; # true
411
".34"->is_decimal; # true
412
"point five"->is_decimal; # false
416
my $module = $module->require;
418
Will C<require> the given $module. This avoids funny things like
419
C<eval qq[require $module] or die $@>. It accepts only module names.
421
On failure it will throw an exception, just like C<require>. On a
422
success it returns the $module. This is mostly useful so that you can
423
immediately call $module's C<import> method to emulate a C<use>.
425
# like "use $module qw(foo bar);" if that worked
426
$module->require->import(qw(foo bar));
428
# like "use $module;" if that worked
429
$module->require->import;
433
my $wrapped = $string->wrap( width => $cols, separator => $sep );
435
Wraps $string to width $cols, breaking lines at word boundries using
438
If no width is given, $cols defaults to 76. Default line separator is
439
the newline character "\n".
441
See L<Text::Wrap> for details.
449
my $trimmed = $string->trim;
450
my $trimmed = $string->trim($character_set);
452
Trim whitespace. ltrim() trims off the start of the string (left),
453
rtrim() off the end (right) and trim() off both the start and end.
455
my $string = ' testme'->ltrim; # 'testme'
456
my $string = 'testme '->rtrim; # 'testme'
457
my $string = ' testme '->trim; # 'testme'
459
They all take an optional $character_set which will determine what
460
characters should be trimmed. It follows regex character set syntax
461
so C<A-Z> will trim everything from A to Z. Defaults to C<\s>,
464
my $string = '-> test <-'->trim('-><'); # ' test '
469
my $name = 'joe smith'->title_case; # Joe Smith
471
Will uppercase every word character that follows a wordbreak character.
476
my $module = $path->path2module;
478
Given a relative $path it will return the Perl module this represents.
481
"Foo/Bar.pm"->path2module; # "Foo::Bar"
483
It will throw an exception if given something which could not be a
484
path to a Perl module.
488
my $path = $module->module2path;
490
Will return the relative $path in which the Perl $module can be found.
493
"Foo::Bar"->module2path; # "Foo/Bar.pm"
498
my $number_grouped = $number->group_digits;
499
my $number_grouped = $number->group_digits(\%options);
501
Turns a number like 1234567 into a string like 1,234,567 known as "digit grouping".
503
It honors your current locale to determine the separator and grouping.
504
This can be overriden using C<%options>.
506
NOTE: many systems do not have their numeric locales set properly
512
The character used to separate groups. Defaults to "thousands_sep" in
513
your locale or "," if your locale doesn't specify.
517
The decimal point character. Defaults to "decimal_point" in your
518
locale or "." if your locale does not specify.
522
How many numbers in a group? Defaults to "grouping" in your locale or
523
3 if your locale doesn't specify.
525
Note: we don't honor the full grouping locale, its a wee bit too complicated.
529
If true, it will treat the number as currency and use the monetary
530
locale settings. "mon_thousands_sep" instead of "thousands_sep" and
531
"mon_grouping" instead of "grouping".
536
1234->group_digits; # 1,234 (assuming US locale)
537
1234->group_digits( separator => "." ); # 1.234
542
my $number_grouped = $number->commify;
543
my $number_grouped = $number->commify(\%options);
545
commify() is just like group_digits() but it is not locale aware. It
546
is useful when you want a predictable result regardless of the user's
549
C<%options> defaults to C<< ( separator => ",", grouping => 3, decimal_point => "." ) >>.
550
Each key will be overriden individually.
552
1234->commify; # 1,234
553
1234->commify({ separator => "." }); # 1.234
556
=head2 List Autoboxing
558
All the functions from L<List::Util> and select ones from
559
L<List::MoreUtils> are all available as methods on unblessed arrays and array refs.
561
first, max, maxstr, min, minstr, minmax, shuffle, reduce, sum, any,
562
all, none, true, false, uniq and mesh.
564
The have all been altered to return array refs where applicable in
565
order to allow chaining.
567
@array->grep(sub{ $_->is_number })->sum->say;
571
@array->foreach( func($item) { ... } );
573
Works like the built in C<foreach>, calls the code block for each
574
element of @array passing it into the block.
576
@array->foreach( func($item) { say $item } ); # print each item
578
It will pass in as many elements as the code block accepts. This
579
allows you to iterate through an array 2 at a time, or 3 or 4 or
582
my @names = ("Joe", "Smith", "Jim", "Dandy", "Jane", "Lane");
583
@names->foreach( func($fname, $lname) {
584
say "Person: $fname $lname";
587
A normal subroutine with no signature will get one at a time.
589
If @array is not a multiple of the iteration (for example, @array has
590
5 elements and you ask 2 at a time) the behavior is currently undefined.
595
Calculate the difference between two (or more) arrays:
600
my @diff_a = @a->diff(\@b) # [ 1, 2 ]
601
my @diff_b = @b->diff(\@a) # [ 4, 5 ]
603
Diff returns all elements in array C<@a> that are not present in array
604
C<@b>. Item order is not considered: two identical elements in both
605
arrays will be recognized as such disregarding their index.
607
[ qw( foo bar ) ]->diff( [ qw( bar foo ) ] ) # empty, they are equal
609
For comparing more than two arrays:
611
@a->diff(\@b, \@c, ... )
613
All comparisons are against the base array (C<@a> in this example). The
614
result will be composed of all those elements that were present in C<@a>
617
It also works with nested data structures; it will traverse them
618
depth-first to assess whether they are identical or not. For instance:
620
[ [ 'foo ' ], { bar => 1 } ]->diff([ 'foo' ]) # [ { bar => 1 } ]
622
In the case of overloaded objects (i.e., L<DateTime>, L<URI>,
623
L<Path::Class>, etc.), it tries its best to treat them as strings or numbers.
625
my $uri = URI->new("http://www.perl.com");
626
my $uri2 = URI->new("http://www.perl.com");
628
[ $uri ]->diff( [ "http://www.perl.com" ] ); # empty, they are equal
629
[ $uri ]->diff( [ $uri2 ] ); # empty, they are equal
637
my @intersection = @a->intersect(\@b) # [ 5 .. 10 ];
639
Performs intersection between arrays, returning those elements that are
640
present in all of the argument arrays simultaneously.
642
As with C<diff()>, it works with any number of arrays, nested data
643
structures of arbitrary depth, and handles overloaded objects
652
my @trimmed = @list->trim;
653
my @trimmed = @list->trim($character_set);
655
Trim whitespace from each element of an array. Each works just like
656
their scalar counterpart.
658
my @trimmed = [ ' foo', 'bar ' ]->ltrim; # [ 'foo', 'bar ' ]
659
my @trimmed = [ ' foo', 'bar ' ]->rtrim; # [ ' foo', 'bar' ]
660
my @trimmed = [ ' foo', 'bar ' ]->trim; # [ 'foo', 'bar' ]
662
As with the scalar trim() methods, they all take an optional $character_set
663
which will determine what characters should be trimmed.
665
my @trimmed = ['-> foo <-', '-> bar <-']->trim('-><'); # [' foo ', ' bar ']
668
=head2 Hash Autoboxing
672
Exchanges values for keys in a hash.
674
my %things = ( foo => 1, bar => 2, baz => 5 );
675
my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz }
677
If there is more than one occurence of a certain value, any one of the
678
keys may end up as the value. This is because of the random ordering
681
# Could be { 1 => foo }, { 1 => bar }, or { 1 => baz }
682
{ foo => 1, bar => 1, baz => 1 }->flip;
684
Because hash references cannot usefully be keys, it will not work on
687
{ foo => [ 'bar', 'baz' ] }->flip; # dies
692
Recursively merge two or more hashes together using L<Hash::Merge::Simple>.
695
my $b = { b => 2, c => 3 };
697
$a->merge($b); # { a => 1, b => 2, c => 3 }
699
For conflicting keys, rightmost precedence is used:
702
my $b = { a => 100, b => 2};
704
$a->merge($b); # { a => 100, b => 2 }
705
$b->merge($a); # { a => 1, b => 2 }
707
It also works with nested hashes, although it won't attempt to merge
708
array references or objects. For more information, look at the
709
L<Hash::Merge::Simple> docs.
713
my %staff = ( bob => 42, martha => 35, timmy => 23 );
714
my %promoted = ( timmy => 23 );
716
%staff->diff(\%promoted); # { bob => 42, martha => 35 }
718
Returns the key/value pairs present in the first hash that are not
719
present in the subsequent hash arguments. Otherwise works as
724
%staff->intersect(\%promoted); # { timmy => 23 }
726
Returns the key/value pairs that are present simultaneously in all the
727
hash arguments. Otherwise works as C<< @array->intersect >>.
729
=head2 Code autoboxing
733
my $sig = $code->signature;
735
You can query the signature of any code reference defined with C<func>
736
or C<method>. See L<Signature Introspection> for details.
738
If C<$code> has a signature, returns an object representing C<$code>'s
739
signature. See L<perl5i::Signature> for details. Otherwise it
745
L<Perl6::Caller> causes C<caller> to return an object in scalar
750
C<die> now always returns an exit code of 255 instead of trying to use
751
C<$!> or C<$?> which makes the exit code unpredictable. If you want
752
to exit with a message and a special exit code, use C<warn> then
757
L<utf8> lets you put UTF8 encoded strings into your source code.
758
This means UTF8 variable and method names, strings and regexes.
760
It means strings will be treated as a set of characters rather than a
761
set of bytes. For example, C<length> will return the number of
762
characters, not the number of bytes.
764
length("perl5i is MËTÁŁ"); # 15, not 18
766
C<@ARGV> will be read as UTF8.
768
STDOUT, STDIN, STDERR and all newly opened filehandles will have UTF8
769
encoding turned on. Consequently, if you want to output raw bytes to
770
a file, such as outputting an image, you must set C<< binmode $fh >>.
774
my($stdout, $stderr) = capture { ... } %options;
775
my $stdout = capture { ... } %options;
777
C<capture()> lets you capture all output to C<STDOUT> and C<STDERR> in
782
my($out, $err) = capture {
787
If called in scalar context, it will only return C<STDOUT> and silence C<STDERR>.
795
C<capture> takes some options.
801
tee will cause output to be captured yet still printed.
803
my $out = capture { print "Hi" } tee => 1;
807
merge will merge C<STDOUT> and C<STDERR> into one variable.
819
C<croak> and C<carp> from L<Carp> are always available.
823
L<Child> provides the C<child> function which is a better way to do forking.
825
C<child> creates and starts a child process, and returns an
826
L<Child::Link::Proc> object which is a better interface for managing the child
827
process. The only required argument is a codeblock, which is called in the new
828
process. exit() is automatically called for you after the codeblock returns.
835
You can also request a pipe for IPC:
840
$parent->say("Message");
841
my $reply = $parent->read();
846
my $message = $proc->read();
849
API Overview: (See L<Child> for more information)
853
=item $proc->is_complete()
857
=item $proc->kill($SIG)
861
=item $proc->exit_status()
865
=item $parent->detach()
867
=item $proc_or_parent->read()
869
=item $proc_or_parent->write( @MESSAGES )
871
=item $proc_or_parent->say( @MESSAGES )
877
L<English> gives English names to the punctuation variables; for
878
instance, C<<$@>> is also C<<$EVAL_ERROR>>. See L<perlvar> for
881
It does B<not> load the regex variables which affect performance.
882
C<$PREMATCH>, C<$MATCH>, and C<$POSTMATCH> will not exist. See
883
the C<p> modifier in L<perlre> for a better alternative.
887
L<Modern::Perl> turns on strict and warnings, enables all the 5.10
888
features like C<given/when>, C<say> and C<state>, and enables C3
889
method resolution order.
893
Provides C<CLASS> and C<$CLASS> alternatives to C<__PACKAGE__>.
897
L<File::chdir> gives you C<$CWD> representing the current working
898
directory and it's assignable to C<chdir>. You can also localize it
899
to safely chdir inside a scope.
903
L<File::stat> causes C<stat> to return an object in scalar context.
907
C<time>, C<localtime>, and C<gmtime> are replaced with DateTime
908
objects. They will all act like the core functions.
910
# Sat Jan 10 13:37:04 2004
911
say scalar gmtime(2**30);
914
say gmtime(2**30)->year;
916
# 2009 (when this was written)
922
C<gmtime()> and C<localtime()> will now safely work with dates beyond
923
the year 2038 and before 1901. The exact range is not defined, but we
924
guarantee at least up to 2**47 and back to year 1.
929
Turns filehandles into objects so you can call methods on them. The
930
biggest one is C<autoflush> rather than mucking around with C<$|> and
938
L<autodie> causes system and file calls which can fail
939
(C<open>, C<system>, and C<chdir>, for example) to die when they fail.
940
This means you don't have to put C<or die> at the end of every system
941
call, but you do have to wrap it in an C<eval> block if you want to
944
autodie's default error messages are pretty smart.
946
All of autodie will be turned on.
949
=head2 autovivification
951
L<autovivification> fixes the bug/feature where this:
956
Results in C<< $hash->{key1} >> coming into existence. That will no longer
959
=head2 No indirect object syntax
961
perl5i turns indirect object syntax, ie. C<new $obj>, into a compile
962
time error. Indirect object syntax is largely unnecessary and
963
removing it avoids a number of ambiguous cases where Perl will
964
mistakenly try to turn a function call into an indirect method call.
966
See L<indirect> for details.
970
C<want()> generalizes the mechanism of the wantarray function, allowing a
971
function to determine the context it's being called in. Want distinguishes
972
not just scalar v. array context, but void, lvalue, rvalue, boolean, reference
973
context, and more. See perldoc L<Want> for full details.
977
L<Try::Tiny> gives support for try/catch blocks as an alternative to
978
C<eval BLOCK>. This allows correct error handling with proper localization
979
of $@ and a nice syntax layer:
981
# handle errors with a catch handler
985
warn "caught error: $_";
988
# just silence errors
993
See perldoc L<Try::Tiny> for details.
998
You no longer have to put a true value at the end of a module which uses perl5i.
1001
=head2 Better load errors
1003
Most of us have learned the meaning of the dreaded "Can't locate Foo.pm in
1004
@INC". Admittedly though, it's not the most helpful of the error messages. In
1005
perl5i we provide a much friendlier error message.
1009
Can't locate My/Module.pm in your Perl library. You may need to install it
1010
from CPAN or another repository. Your library paths are:
1011
Indented list of paths, 1 per line...
1013
=head1 Command line program
1015
There is a perl5i command line program installed with perl5i (Windows
1016
users get perl5i.bat). This is handy for writing one liners.
1018
perl5i -e 'gmtime->year->say'
1020
And you can use it on the C<#!> line.
1029
Some parts are not lexical. Some parts are package scoped.
1031
If you're going to use two versions of perl5i together, we do not
1032
currently recommend having them in the same package.
1034
See L<http://github.com/schwern/perl5i/issues/labels/bug> for a complete list.
1036
Please report bugs at L<http://github.com/schwern/perl5i/issues/> or
1037
email L<mailto:perl5i@googlegroups.com>.
1042
perl5i follows the Semantic Versioning policy, L<http://semver.org>.
1045
Versions will be of the form X.Y.Z.
1047
0.Y.Z may change anything at any time.
1049
Incrementing X (ie. 1.2.3 -> 2.0.0) indicates a backwards incompatible change.
1051
Incrementing Y (ie. 1.2.3 -> 1.3.0) indicates a new feature.
1053
Incrementing Z (ie. 1.2.3 -> 1.2.4) indicates a bug fix or other internal change.
1058
Inspired by chromatic's L<Modern::Perl> and in particular
1059
F<http://www.modernperlbooks.com/mt/2009/04/ugly-perl-a-lesson-in-the-importance-of-language-design.html>.
1061
I totally didn't come up with the "Perl 5 + i" joke. I think it was
1067
Thanks to our contributors: Chas Owens, Darian Patrick, rjbs,
1068
chromatic, Ben Hengst, Bruno Vecchi and anyone else I've forgotten.
1070
Thanks to Flavian and Matt Trout for their signature and
1071
L<Devel::Declare> work.
1073
Thanks to all the CPAN authors upon whom this builds.
1077
Copyright 2009-2010, Michael G Schwern <schwern@pobox.com>
1079
This program is free software; you can redistribute it and/or
1080
modify it under the same terms as Perl itself.
1082
See L<http://dev.perl.org/licenses/artistic.html>
1087
Repository: L<http://github.com/schwern/perl5i/tree/master>
1088
Issues/Bugs: L<http://github.com/schwern/perl5i/issues>
1089
IRC: irc.perl.org on the #perl5i channel
1090
Mailing List: L<http://groups.google.com/group/perl5i/>
1092
Frequently Asked Questions about perl5i: L<perl5ifaq>
1094
Some modules with similar purposes include:
1095
L<Modern::Perl>, L<Common::Sense>
1097
For a complete object declaration system, see L<Moose> and