1perl5i(3) User Contributed Perl Documentation perl5i(3)
2
3
4
6 perl5i - Fix as much of Perl 5 as possible in one pragma
7
9 use perl5i::2;
10
11 or
12
13 $ perl5i your_script.pl
14
16 Perl 5 has a lot of warts. There's a lot of individual modules and
17 techniques out there to fix those warts. perl5i aims to pull the best
18 of them together into one module so you can turn them on all at once.
19
20 This includes adding features, changing existing core functions and
21 changing defaults. It will likely not be 100% backwards compatible
22 with Perl 5, though it will be 99%, perl5i will try to have a lexical
23 effect.
24
25 Please add to this imaginary world and help make it real, either by
26 telling me what Perl looks like in your imagination
27 (http://github.com/evalEmpire/perl5i/issues) or make a fork (forking on
28 github is like a branch you control) and implement it yourself.
29
31 Changing perl 5 core is a slow and difficult process. Perl 5 aims to
32 be compatible with ancient versions which means it is mostly stuck with
33 design, decisions and defaults made way back in the 90's.
34
35 There are modules in CPAN to solve or ease many of those issues but
36 many people don't know about them or don't know which ones to use.
37
38 Documentation and books are updated slowly and don't usually keep up;
39 this information becomes some sort of community knowledge, invisible
40 from the wider audience.
41
42 Even if you know a solution, having to decide everytime which module to
43 use and enable it individually might be enough for you to give up and
44 just do things the old way.
45
46 Perl5i brings all this community knowledge in a coherent way, in
47 something like 'the best of CPAN', enabled with a single command.
48
49 You don't need to know all it does nor how it does it, you just "use
50 perl5i::2" on your code and you automatically get a modern environment,
51 with perl defaults, problems and inconsistencies fixed.
52
53 You can refer beginers to perl5i and they can benefit from it without
54 needing to become a perl guru first.
55
57 Because perl5i plans to be incompatible in the future, you do not
58 simply "use perl5i". You must declare which major version of perl5i
59 you are using. You do this like so:
60
61 # Use perl5i major version 2
62 use perl5i::2;
63
64 Thus the code you write with, for example, "perl5i::2" will always
65 remain compatible even as perl5i moves on.
66
67 If you want to be daring, you can "use perl5i::latest" to get the
68 latest version. This will automatically happen if the program is "-e".
69 This lets you do slightly less typing for one-liners like "perl
70 -Mperl5i -e ..."
71
72 If you want your module to depend on perl5i, you should depend on the
73 versioned class. For example, depend on "perl5i::2" and not "perl5i".
74
75 See "VERSIONING" for more information about perl5i's versioning scheme.
76
78 perl5i enables each of these modules and adds/changes these functions.
79 We'll provide a brief description here, but you should look at each of
80 their documentation for full details.
81
82 The Meta Object
83 Every object (and everything is an object) now has a meta object
84 associated with it. Using the meta object you can ask things about the
85 object which were previously over complicated. For example...
86
87 # the object's class
88 my $class = $obj->mo->class;
89
90 # its parent classes
91 my @isa = $obj->mo->isa;
92
93 # the complete inheritance hierarchy
94 my @complete_isa = $obj->mo->linear_isa;
95
96 # the reference type of the object
97 my $reftype = $obj->mo->reftype;
98
99 A meta object is used to avoid polluting the global method space. "mo"
100 was chosen to avoid clashing with Moose's meta object.
101
102 See perl5i::Meta for complete details.
103
104 Subroutine and Method Signatures
105 perl5i makes it easier to declare what parameters a subroutine takes.
106
107 func hello($place) {
108 say "Hello, $place!\n";
109 }
110
111 method get($key) {
112 return $self->{$key};
113 }
114
115 method new($class: %args) {
116 return bless \%args, $class;
117 }
118
119 "func" and "method" define subroutines as "sub" does, with some extra
120 conveniences.
121
122 The signature syntax is currently very simple. The content will be
123 assigned from @_. This:
124
125 func add($this, $that) {
126 return $this + $that;
127 }
128
129 is equivalent to:
130
131 sub add {
132 my($this, $that) = @_;
133 return $this + $that;
134 }
135
136 "method" defines a method. This is the same as a subroutine, but the
137 first argument, the invocant, will be removed and made into $self.
138
139 method get($key) {
140 return $self->{$key};
141 }
142
143 sub get {
144 my $self = shift;
145 my($key) = @_;
146 return $self->{$key};
147 }
148
149 Methods have a special bit of syntax. If the first item in the
150 signature is $var: it will change the variable used to store the
151 invocant.
152
153 method new($class: %args) {
154 return bless \%args, $class;
155 }
156
157 is equivalent to:
158
159 sub new {
160 my $class = shift;
161 my %args = @_;
162 return bless \%args, $class;
163 }
164
165 Anonymous functions and methods work, too.
166
167 my $code = func($message) { say $message };
168
169 Guarantees include:
170
171 @_ will not be modified except by removing the invocant
172
173 Future versions of perl5i will add to the signature syntax and
174 capabilities. Planned expansions include:
175
176 Signature validation
177 Signature documentation
178 Named parameters
179 Required parameters
180 Read only parameters
181 Aliased parameters
182 Anonymous method and function declaration
183 Variable method and function names
184 Parameter traits
185 Traditional prototypes
186
187 See <http://github.com/evalEmpire/perl5i/issues/labels/syntax#issue/19>
188 for more details about future expansions.
189
190 The equivalencies above should only be taken for illustrative purposes,
191 they are not guaranteed to be literally equivalent.
192
193 Note that while all parameters are optional by default, the number of
194 parameters will eventually be enforced. For example, right now this
195 will work:
196
197 func add($this, $that) { return $this + $that }
198
199 say add(1,2,3); # says 3
200
201 The extra argument is ignored. In future versions of perl5i this will
202 be a runtime error.
203
204 Signature Introspection
205
206 The signature of a subroutine defined with "func" or "method" can be
207 queried by calling the "signature" method on the code reference.
208
209 func hello($greeting, $place) { say "$greeting, $place" }
210
211 my $code = \&hello;
212 say $code->signature->num_positional_params; # prints 2
213
214 Functions defined with "sub" will not have a signature.
215
216 See perl5i::Signature for more details.
217
218 Autoboxing
219 autobox allows methods to be defined for and called on most unblessed
220 variables. This means you can call methods on ordinary strings, lists
221 and hashes! It also means perl5i can add a lot of functionality
222 without polluting the global namespace.
223
224 autobox::Core wraps a lot of Perl's built in functions so they can be
225 called as methods on unblessed variables. "@a->pop" for example.
226
227 alias
228
229 $scalar_reference->alias( @identifiers );
230 @alias->alias( @identifiers );
231 %hash->alias( @identifiers );
232 (\&code)->alias( @identifiers );
233
234 Aliases a variable to a new global name.
235
236 my $code = sub { 42 };
237 $code->alias( "foo" );
238 say foo(); # prints 42
239
240 It will work on everything except scalar references.
241
242 our %stuff;
243 %other_hash->alias( "stuff" ); # %stuff now aliased to %other_hash
244
245 It is not a copy, changes to one will change the other.
246
247 my %things = (foo => 23);
248 our %stuff;
249 %things->alias( "stuff" ); # alias %things to %stuff
250 $stuff{foo} = 42; # change %stuff
251 say $things{foo}; # and it will show up in %things
252
253 Multiple @identifiers will be joined with '::' and used as the fully
254 qualified name for the alias.
255
256 my $class = "Some::Class";
257 my $name = "foo";
258 sub { 99 }->alias( $class, $name );
259 say Some::Class->foo; # prints 99
260
261 If there is just one @identifier and it has no "::" in it, the current
262 caller will be prepended. "$thing->alias("name")" is shorthand for
263 "$thing->alias(CLASS, "name")"
264
265 Due to limitations in autobox, non-reference scalars cannot be aliased.
266 Alias a scalar ref instead.
267
268 my $thing = 23;
269 $thing->alias("foo"); # error
270
271 my $thing = \23;
272 $thing->alias("foo"); # $foo is now aliased to $thing
273
274 This is basically a nicer way to say:
275
276 no strict 'refs';
277 *{$package . '::'. $name} = $reference;
278
279 Scalar Autoboxing
280 All of the methods provided by autobox::Core are available from perl5i.
281
282 in addition, perl5i adds some methods of its own.
283
284 path
285
286 my $object = $path->path;
287
288 Creates a Path::Tiny $object for the given file or directory $path.
289
290 my $path = "/foo/bar/baz.txt"->path;
291 my $content = $path->slurp;
292
293 center
294
295 my $centered_string = $string->center($length);
296 my $centered_string = $string->center($length, $character);
297
298 Centers $string between $character. $centered_string will be of length
299 $length.
300
301 $character defaults to " ".
302
303 say "Hello"->center(10); # " Hello ";
304 say "Hello"->center(10, '-'); # "---Hello--";
305
306 "center()" will never truncate $string. If $length is less than
307 "$string->length" it will just return $string.
308
309 say "Hello"->center(4); # "Hello";
310
311 round
312
313 my $rounded_number = $number->round;
314
315 Round to the nearest integer.
316
317 round_up
318
319 ceil
320
321 my $new_number = $number->round_up;
322
323 Rounds the $number towards infinity.
324
325 2.45->round_up; # 3
326 (-2.45)->round_up; # -2
327
328 ceil() is a synonym for round_up().
329
330 round_down
331
332 floor
333
334 my $new_number = $number->round_down;
335
336 Rounds the $number towards negative infinity.
337
338 2.45->round_down; # 2
339 (-2.45)->round_down; # -3
340
341 floor() is a synonyn for round_down().
342
343 is_number
344
345 $is_a_number = $thing->is_number;
346
347 Returns true if $thing is a number understood by Perl.
348
349 12.34->is_number; # true
350 "12.34"->is_number; # also true
351 "eleven"->is_number; # false
352
353 is_positive
354
355 $is_positive = $thing->is_positive;
356
357 Returns true if $thing is a positive number.
358
359 0 is not positive.
360
361 is_negative
362
363 $is_negative = $thing->is_negative;
364
365 Returns true if $thing is a negative number.
366
367 0 is not negative.
368
369 is_even
370
371 $is_even = $thing->is_even;
372
373 Returns true if $thing is an even integer.
374
375 is_odd
376
377 $is_odd = $thing->is_odd;
378
379 Returns true if $thing is an odd integer.
380
381 is_integer
382
383 $is_an_integer = $thing->is_integer;
384
385 Returns true if $thing is an integer.
386
387 12->is_integer; # true
388 12.34->is_integer; # false
389 "eleven"->is_integer; # false
390
391 is_int
392
393 A synonym for is_integer
394
395 is_decimal
396
397 $is_a_decimal_number = $thing->is_decimal;
398
399 Returns true if $thing is a decimal number.
400
401 12->is_decimal; # false
402 12.34->is_decimal; # true
403 ".34"->is_decimal; # true
404 "point five"->is_decimal; # false
405
406 require
407
408 my $module = $module->require;
409
410 Will "require" the given $module. This avoids funny things like "eval
411 qq[require $module] or die $@". It accepts only module names.
412
413 On failure it will throw an exception, just like "require". On a
414 success it returns the $module. This is mostly useful so that you can
415 immediately call $module's "import" method to emulate a "use".
416
417 # like "use $module qw(foo bar);" if that worked
418 $module->require->import(qw(foo bar));
419
420 # like "use $module;" if that worked
421 $module->require->import;
422
423 wrap
424
425 my $wrapped = $string->wrap( width => $cols, separator => $sep );
426
427 Wraps $string to width $cols, breaking lines at word boundries using
428 separator $sep.
429
430 If no width is given, $cols defaults to 76. Default line separator is
431 the newline character "\n".
432
433 See Text::Wrap for details.
434
435 ltrim
436
437 rtrim
438
439 trim
440
441 my $trimmed = $string->trim;
442 my $trimmed = $string->trim($character_set);
443
444 Trim whitespace. ltrim() trims off the start of the string (left),
445 rtrim() off the end (right) and trim() off both the start and end.
446
447 my $string = ' testme'->ltrim; # 'testme'
448 my $string = 'testme '->rtrim; # 'testme'
449 my $string = ' testme '->trim; # 'testme'
450
451 They all take an optional $character_set which will determine what
452 characters should be trimmed. It follows regex character set syntax so
453 "A-Z" will trim everything from A to Z. Defaults to "\s", whitespace.
454
455 my $string = '-> test <-'->trim('-><'); # ' test '
456
457 title_case
458
459 my $name = 'joe smith'->title_case; # Joe Smith
460
461 Will uppercase every word character that follows a wordbreak character.
462
463 path2module
464
465 my $module = $path->path2module;
466
467 Given a relative $path it will return the Perl module this represents.
468 For example,
469
470 "Foo/Bar.pm"->path2module; # "Foo::Bar"
471
472 It will throw an exception if given something which could not be a path
473 to a Perl module.
474
475 module2path
476
477 my $path = $module->module2path;
478
479 Will return the relative $path in which the Perl $module can be found.
480 For example,
481
482 "Foo::Bar"->module2path; # "Foo/Bar.pm"
483
484 is_module_name
485
486 my $is_valid = $string->is_module_name;
487
488 Will return true if the $string is a valid module name.
489
490 "Foo::Bar"->is_module_name; # true
491 "Foo/Bar"->is_module_name; # false
492
493 group_digits
494
495 my $number_grouped = $number->group_digits;
496 my $number_grouped = $number->group_digits(\%options);
497
498 Turns a number like 1234567 into a string like 1,234,567 known as
499 "digit grouping".
500
501 It honors your current locale to determine the separator and grouping.
502 This can be overridden using %options.
503
504 NOTE: many systems do not have their numeric locales set properly
505
506 separator
507 The character used to separate groups. Defaults to "thousands_sep"
508 in your locale or "," if your locale doesn't specify.
509
510 decimal_point
511 The decimal point character. Defaults to "decimal_point" in your
512 locale or "." if your locale does not specify.
513
514 grouping
515 How many numbers in a group? Defaults to "grouping" in your locale
516 or 3 if your locale doesn't specify.
517
518 Note: we don't honor the full grouping locale, its a wee bit too
519 complicated.
520
521 currency
522 If true, it will treat the number as currency and use the monetary
523 locale settings. "mon_thousands_sep" instead of "thousands_sep"
524 and "mon_grouping" instead of "grouping".
525
526 1234->group_digits; # 1,234 (assuming US locale)
527 1234->group_digits( separator => "." ); # 1.234
528
529 commify
530
531 my $number_grouped = $number->commify;
532 my $number_grouped = $number->commify(\%options);
533
534 commify() is just like group_digits() but it is not locale aware. It
535 is useful when you want a predictable result regardless of the user's
536 locale settings.
537
538 %options defaults to "( separator => ",", grouping => 3, decimal_point
539 => "." )". Each key will be overridden individually.
540
541 1234->commify; # 1,234
542 1234->commify({ separator => "." }); # 1.234
543
544 reverse
545
546 my $reverse = $string->reverse;
547
548 Reverses a $string.
549
550 Unlike Perl's reverse(), this always reverses the string regardless of
551 context.
552
553 Array Autoboxing
554 The methods provided by "Array Methods" in autobox::Core are available
555 from perl5i.
556
557 All the functions from List::Util and select ones from List::MoreUtils
558 are all available as methods on unblessed arrays and array refs: first,
559 max, maxstr, min, minstr, minmax, shuffle, reduce, sum, any, all, none,
560 true, false, uniq and mesh.
561
562 They have all been altered to return array refs where applicable in
563 order to allow chaining.
564
565 @array->grep(sub{ $_->is_number })->sum->say;
566
567 foreach
568
569 @array->foreach( func($item) { ... } );
570
571 Works like the built in "foreach", calls the code block for each
572 element of @array passing it into the block.
573
574 @array->foreach( func($item) { say $item } ); # print each item
575
576 It will pass in as many elements as the code block accepts. This
577 allows you to iterate through an array 2 at a time, or 3 or 4 or
578 whatever.
579
580 my @names = ("Joe", "Smith", "Jim", "Dandy", "Jane", "Lane");
581 @names->foreach( func($fname, $lname) {
582 say "Person: $fname $lname";
583 });
584
585 A normal subroutine with no signature will get one at a time.
586
587 If @array is not a multiple of the iteration (for example, @array has 5
588 elements and you ask 2 at a time) the behavior is currently undefined.
589
590 as_hash
591
592 my %hash = @array->as_hash;
593
594 This method returns a %hash where each element of @array is a key. The
595 values are all true. Its functionality is similar to:
596
597 my %hash = map { $_ => 1 } @array;
598
599 Example usage:
600
601 my @array = ("a", "b", "c");
602 my %hash = @array->as_hash;
603 say q[@array contains 'a'] if $hash{"a"};
604
605 pick
606
607 my @rand = @array->pick($number);
608
609 The pick() method returns a list of $number elements in @array. If
610 $number is larger than the size of the list, it returns the entire list
611 shuffled.
612
613 Example usage:
614
615 my @array = (1, 2, 3, 4);
616 my @rand = @array->pick(2);
617
618 pick_one
619
620 my $rand = @array->pick_one;
621
622 The pick_one() method returns a random element in @array. It is
623 similar to @array->pick(1), except that it does not return a list.
624
625 Example usage:
626
627 my @array = (1,2,3,4);
628 my $rand = @array->pick_one;
629
630 diff
631
632 Calculate the difference between two (or more) arrays:
633
634 my @a = ( 1, 2, 3 );
635 my @b = ( 3, 4, 5 );
636
637 my @diff_a = @a->diff(\@b) # [ 1, 2 ]
638 my @diff_b = @b->diff(\@a) # [ 4, 5 ]
639
640 Diff returns all elements in array @a that are not present in array @b.
641 Item order is not considered: two identical elements in both arrays
642 will be recognized as such disregarding their index.
643
644 [ qw( foo bar ) ]->diff( [ qw( bar foo ) ] ) # empty, they are equal
645
646 For comparing more than two arrays:
647
648 @a->diff(\@b, \@c, ... )
649
650 All comparisons are against the base array (@a in this example). The
651 result will be composed of all those elements that were present in @a
652 and in none other.
653
654 It also works with nested data structures; it will traverse them depth-
655 first to assess whether they are identical or not. For instance:
656
657 [ [ 'foo ' ], { bar => 1 } ]->diff([ 'foo' ]) # [ { bar => 1 } ]
658
659 In the case of overloaded objects (i.e., DateTime, URI, Path::Class,
660 etc.), it tries its best to treat them as strings or numbers.
661
662 my $uri = URI->new("http://www.perl.com");
663 my $uri2 = URI->new("http://www.perl.com");
664
665 [ $uri ]->diff( [ "http://www.perl.com" ] ); # empty, they are equal
666 [ $uri ]->diff( [ $uri2 ] ); # empty, they are equal
667
668 popn
669
670 my @newarray = @array->popn($n);
671
672 Pops $n values from the @array.
673
674 If $n is greater than the length of @array, it will return the whole
675 @array. If $n is 0, it will return an empty array.
676
677 A negative $n or non-integer is an error.
678
679 my @array = (1, 2, 3, 4, 5);
680 my @newarray = @array->popn(3); # (3, 4, 5)
681
682 shiftn
683
684 my @newarray = @array->shiftn($n);
685
686 Works like popn, but it shifts off the front of the array instead of
687 popping off the end.
688
689 my @array = (1, 2, 3, 4, 5);
690 my @newarray = @array->shiftn(3); # (1, 2, 3)
691
692 intersect
693
694 my @a = (1 .. 10);
695 my @b = (5 .. 15);
696
697 my @intersection = @a->intersect(\@b) # [ 5 .. 10 ];
698
699 Performs intersection between arrays, returning those elements that are
700 present in all of the argument arrays simultaneously.
701
702 As with "diff()", it works with any number of arrays, nested data
703 structures of arbitrary depth, and handles overloaded objects
704 graciously.
705
706 ltrim
707
708 rtrim
709
710 trim
711
712 my @trimmed = @list->trim;
713 my @trimmed = @list->trim($character_set);
714
715 Trim whitespace from each element of an array. Each works just like
716 their scalar counterpart.
717
718 my @trimmed = [ ' foo', 'bar ' ]->ltrim; # [ 'foo', 'bar ' ]
719 my @trimmed = [ ' foo', 'bar ' ]->rtrim; # [ ' foo', 'bar' ]
720 my @trimmed = [ ' foo', 'bar ' ]->trim; # [ 'foo', 'bar' ]
721
722 As with the scalar trim() methods, they all take an optional
723 $character_set which will determine what characters should be trimmed.
724
725 my @trimmed = ['-> foo <-', '-> bar <-']->trim('-><'); # [' foo ', ' bar ']
726
727 Hash Autoboxing
728 All of the methods provided by "Hash Methods" in autobox::Core are
729 available from perl5i.
730
731 In addition...
732
733 each
734
735 Iterate through each key/value pair in a hash using a callback.
736
737 my %things = ( foo => 23, bar => 42 );
738 %things->each( func($k, $v) {
739 say "Key: $k, Value: $v"
740 });
741
742 Unlike the "each" function, individual calls to each are guaranteed to
743 iterate through the entirety of the hash.
744
745 flip
746
747 Exchanges values for keys in a hash.
748
749 my %things = ( foo => 1, bar => 2, baz => 5 );
750 my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz }
751
752 If there is more than one occurrence of a certain value, any one of the
753 keys may end up as the value. This is because of the random ordering
754 of hash keys.
755
756 # Could be { 1 => foo }, { 1 => bar }, or { 1 => baz }
757 { foo => 1, bar => 1, baz => 1 }->flip;
758
759 Because hash references cannot usefully be keys, it will not work on
760 nested hashes.
761
762 { foo => [ 'bar', 'baz' ] }->flip; # dies
763
764 merge
765
766 Recursively merge two or more hashes together using
767 Hash::Merge::Simple.
768
769 my $a = { a => 1 };
770 my $b = { b => 2, c => 3 };
771
772 $a->merge($b); # { a => 1, b => 2, c => 3 }
773
774 For conflicting keys, rightmost precedence is used:
775
776 my $a = { a => 1 };
777 my $b = { a => 100, b => 2};
778
779 $a->merge($b); # { a => 100, b => 2 }
780 $b->merge($a); # { a => 1, b => 2 }
781
782 It also works with nested hashes, although it won't attempt to merge
783 array references or objects. For more information, look at the
784 Hash::Merge::Simple docs.
785
786 diff
787
788 my %staff = ( bob => 42, martha => 35, timmy => 23 );
789 my %promoted = ( timmy => 23 );
790
791 %staff->diff(\%promoted); # { bob => 42, martha => 35 }
792
793 Returns the key/value pairs present in the first hash that are not
794 present in the subsequent hash arguments. Otherwise works as
795 "@array->diff".
796
797 intersect
798
799 %staff->intersect(\%promoted); # { timmy => 23 }
800
801 Returns the key/value pairs that are present simultaneously in all the
802 hash arguments. Otherwise works as "@array->intersect".
803
804 Code autoboxing
805 signature
806
807 my $sig = $code->signature;
808
809 You can query the signature of any code reference defined with "func"
810 or "method". See "Signature Introspection" for details.
811
812 If $code has a signature, returns an object representing $code's
813 signature. See perl5i::Signature for details. Otherwise it returns
814 nothing.
815
816 caller
817
818 Perl6::Caller causes "caller" to return an object in scalar context.
819
820 die
821
822 "die" now always returns an exit code of 255 instead of trying to use
823 $! or $? which makes the exit code unpredictable. If you want to exit
824 with a message and a special exit code, use "warn" then "exit".
825
826 list
827
828 "list" will force list context similar to how scalar will force scalar
829 context.
830
831 utf8::all
832 perl5i turns on utf8::all which turns on all the Unicode features of
833 Perl it can.
834
835 Here is the current list, more may be turned on later.
836
837 Bare strings in your source code are now UTF8. This means UTF8
838 variable and method names, strings and regexes.
839
840 my $message = "XXX XX XXXXX XXXXXXX";
841 my $XXXX = "It's all Greek to me!";
842 sub fuenksshuen~ { ... }
843
844 Strings will be treated as a set of characters rather than a set of
845 bytes. For example, "length" will return the number of characters, not
846 the number of bytes.
847
848 length("perl5i is MEeTAX"); # 15, not 18
849
850 @ARGV will be read as UTF8.
851
852 STDOUT, STDIN, STDERR and all newly opened filehandles will have UTF8
853 encoding turned on. Consequently, if you want to output raw bytes to a
854 file, such as outputting an image, you must set "binmode $fh".
855
856 capture
857
858 my($stdout, $stderr) = capture { ... } %options;
859 my $stdout = capture { ... } %options;
860
861 "capture()" lets you capture all output to "STDOUT" and "STDERR" in any
862 block of code.
863
864 # $out = "Hello"
865 # $err = "Bye"
866 my($out, $err) = capture {
867 print "Hello";
868 print STDERR "Bye";
869 };
870
871 If called in scalar context, it will only return "STDOUT" and silence
872 "STDERR".
873
874 # $out = "Hello"
875 my $out = capture {
876 print "Hello";
877 warn "oh god";
878 };
879
880 "capture" takes some options.
881
882 tee tee will cause output to be captured yet still printed.
883
884 my $out = capture { print "Hi" } tee => 1;
885
886 merge
887 merge will merge "STDOUT" and "STDERR" into one variable.
888
889 # $out = "HiBye"
890 my $out = capture {
891 print "Hi";
892 print STDERR "Bye";
893 } merge => 1;
894
895 Carp
896 "croak" and "carp" from Carp are always available.
897
898 The Carp message will always format consistently, smoothing over the
899 backwards incompatible change in Carp 1.25.
900
901 Child
902 Child provides the "child" function which is a better way to do
903 forking.
904
905 "child" creates and starts a child process, and returns an
906 Child::Link::Proc object which is a better interface for managing the
907 child process. The only required argument is a codeblock, which is
908 called in the new process. exit() is automatically called for you after
909 the codeblock returns.
910
911 my $proc = child {
912 my $parent = shift;
913 ...
914 };
915
916 You can also request a pipe for IPC:
917
918 my $proc = child {
919 my $parent = shift;
920
921 $parent->say("Message");
922 my $reply = $parent->read();
923
924 ...
925 } pipe => 1;
926
927 my $message = $proc->read();
928 $proc->say("reply");
929
930 See Child for more information.
931
932 English
933 English gives English names to the punctuation variables; for instance,
934 "<$@"> is also "<$EVAL_ERROR">. See perlvar for details.
935
936 It does not load the regex variables which affect performance.
937 $PREMATCH, $MATCH, and $POSTMATCH will not exist. See the "p" modifier
938 in perlre for a better alternative.
939
940 Modern::Perl
941 Modern::Perl turns on strict and warnings, enables all the 5.10
942 features like "given/when", "say" and "state", and enables C3 method
943 resolution order.
944
945 CLASS
946 Provides "CLASS" and $CLASS alternatives to "__PACKAGE__".
947
948 File::chdir
949 File::chdir gives you $CWD representing the current working directory
950 and it's assignable to "chdir". You can also localize it to safely
951 chdir inside a scope.
952
953 File::stat
954 File::stat causes "stat" to return an object in scalar context.
955
956 DateTime
957 "time", "localtime", and "gmtime" are replaced with DateTime objects.
958 They will all act like the core functions.
959
960 # Sat Jan 10 13:37:04 2004
961 say scalar gmtime(2**30);
962
963 # 2004
964 say gmtime(2**30)->year;
965
966 # 2009 (when this was written)
967 say time->year;
968
969 Time::y2038
970 "gmtime()" and "localtime()" will now safely work with dates beyond the
971 year 2038 and before 1901. The exact range is not defined, but we
972 guarantee at least up to 2**47 and back to year 1.
973
974 IO::Handle
975 Turns filehandles into objects so you can call methods on them. The
976 biggest one is "autoflush" rather than mucking around with $| and
977 "select".
978
979 $fh->autoflush(1);
980
981 autodie
982 autodie causes system and file calls which can fail ("open", "system",
983 and "chdir", for example) to die when they fail. This means you don't
984 have to put "or die" at the end of every system call, but you do have
985 to wrap it in an "eval" block if you want to trap the failure.
986
987 autodie's default error messages are pretty smart.
988
989 All of autodie will be turned on.
990
991 autovivification
992 autovivification fixes the bug/feature where this:
993
994 $hash = {};
995 $hash->{key1}{key2};
996
997 Results in "$hash->{key1}" coming into existence. That will no longer
998 happen.
999
1000 No indirect object syntax
1001 perl5i turns indirect object syntax, ie. "new $obj", into a compile
1002 time error. Indirect object syntax is largely unnecessary and removing
1003 it avoids a number of ambiguous cases where Perl will mistakenly try to
1004 turn a function call into an indirect method call.
1005
1006 See indirect for details.
1007
1008 want
1009
1010 "want()" generalizes the mechanism of the wantarray function, allowing
1011 a function to determine the context it's being called in. Want
1012 distinguishes not just scalar v. array context, but void, lvalue,
1013 rvalue, boolean, reference context, and more. See perldoc Want for
1014 full details.
1015
1016 Try::Tiny
1017 Try::Tiny gives support for try/catch blocks as an alternative to "eval
1018 BLOCK". This allows correct error handling with proper localization of
1019 $@ and a nice syntax layer:
1020
1021 # handle errors with a catch handler
1022 try {
1023 die "foo";
1024 } catch {
1025 warn "caught error: $_";
1026 };
1027
1028 # just silence errors
1029 try {
1030 die "foo";
1031 };
1032
1033 See perldoc Try::Tiny for details.
1034
1035 true
1036 You no longer have to put a true value at the end of a module which
1037 uses perl5i.
1038
1039 Better load errors
1040 Most of us have learned the meaning of the dreaded "Can't locate Foo.pm
1041 in @INC". Admittedly though, it's not the most helpful of the error
1042 messages. In perl5i we provide a much friendlier error message.
1043
1044 Example:
1045
1046 Can't locate My/Module.pm in your Perl library. You may need to install it
1047 from CPAN or another repository. Your library paths are:
1048 Indented list of paths, 1 per line...
1049
1051 use perl5i::2 -skip => \@features_to_skip;
1052
1053 While perl5i is intended as a curated collection of modules, its
1054 possible you might not want certain features. Features can be turned
1055 off in your scope by using "-skip".
1056
1057 For example, this will skip loading Try::Tiny.
1058
1059 use perl5i::latest -skip => [qw(Try::Tiny)];
1060
1061 Why would you do this? You might want to use a different try/catch
1062 module such as TryCatch which provides its own "try" and "catch".
1063
1064 The feature strings are: "autobox", "autodie", "autovivification",
1065 "capture", "Carp::Fix::1_25", "Child", "CLASS", "die", "English",
1066 "File::chdir", "indirect", "list", "Meta", "Modern::Perl",
1067 "Perl6::Caller", "Signatures", "stat", "time", "true", "Try::Tiny",
1068 "utf8::all", "Want".
1069
1071 There is a perl5i command line program installed with perl5i (Windows
1072 users get perl5i.bat). This is handy for writing one liners.
1073
1074 perl5i -e 'gmtime->year->say'
1075
1076 And you can use it on the "#!" line.
1077
1078 #!/usr/bin/perl5i
1079
1080 gmtime->year->say;
1081
1082 If you write a one-liner without using this program, saying "-Mperl5i"
1083 means "-Mperl5i::latest". Please see "Using perl5i" and "VERSIONING"
1084 for details.
1085
1087 Some parts are not lexical. Some parts are package scoped.
1088
1089 If you're going to use two versions of perl5i together, we do not
1090 currently recommend having them in the same package.
1091
1092 See <http://github.com/evalEmpire/perl5i/issues/labels/bug> for a
1093 complete list.
1094
1095 Please report bugs at <http://github.com/evalEmpire/perl5i/issues/>.
1096
1098 perl5i follows the Semantic Versioning policy, <http://semver.org>. In
1099 short...
1100
1101 Versions will be of the form X.Y.Z.
1102
1103 0.Y.Z may change anything at any time.
1104
1105 Incrementing X (ie. 1.2.3 -> 2.0.0) indicates a backwards incompatible
1106 change.
1107
1108 Incrementing Y (ie. 1.2.3 -> 1.3.0) indicates a new feature.
1109
1110 Incrementing Z (ie. 1.2.3 -> 1.2.4) indicates a bug fix or other
1111 internal change.
1112
1114 Inspired by chromatic's Modern::Perl and in particular
1115 http://www.modernperlbooks.com/mt/2009/04/ugly-perl-a-lesson-in-the-importance-of-language-design.html.
1116
1117 I totally didn't come up with the "Perl 5 + i" joke. I think it was
1118 Damian Conway.
1119
1121 Thanks to our contributors: Chas Owens, Darian Patrick, rjbs,
1122 chromatic, Ben Hengst, Bruno Vecchi and anyone else I've forgotten.
1123
1124 Thanks to Flavian and Matt Trout for their signature and Devel::Declare
1125 work.
1126
1127 Thanks to all the CPAN authors upon whom this builds.
1128
1130 Copyright 2009-2010, Michael G Schwern <schwern@pobox.com>
1131
1132 This program is free software; you can redistribute it and/or modify it
1133 under the same terms as Perl itself.
1134
1135 See <http://dev.perl.org/licenses/artistic.html>
1136
1138 Repository: <http://github.com/evalEmpire/perl5i/> Issues/Bugs:
1139 <http://github.com/evalEmpire/perl5i/issues> IRC:
1140 <irc://irc.perl.org> on the #perl5i channel Wiki:
1141 <http://github.com/evalEmpire/perl5i/wiki> Twitter:
1142 <http://twitter.com/perl5i>
1143
1144 Frequently Asked Questions about perl5i: perl5ifaq
1145
1146 Some modules with similar purposes include: Modern::Perl, Common::Sense
1147
1148 For a complete object declaration system, see Moose and
1149 MooseX::Declare.
1150
1151
1152
1153perl v5.30.1 2020-01-30 perl5i(3)