evalempire / perl5i Goto Github PK
View Code? Open in Web Editor NEWA single module to fix as much of Perl 5 as possible in one go
Home Page: http://search.cpan.org/perldoc?perl5i
License: Other
A single module to fix as much of Perl 5 as possible in one go
Home Page: http://search.cpan.org/perldoc?perl5i
License: Other
NAME perl5i - Fix as much of Perl 5 as possible in one pragma SYNOPSIS use perl5i::2; or $ perl5i your_script.pl DESCRIPTION Perl 5 has a lot of warts. There's a lot of individual modules and techniques out there to fix those warts. perl5i aims to pull the best of them together into one module so you can turn them on all at once. This includes adding features, changing existing core functions and changing defaults. It will likely not be 100% backwards compatible with Perl 5, though it will be 99%, perl5i will try to have a lexical effect. Please add to this imaginary world and help make it real, either by telling me what Perl looks like in your imagination (http://github.com/evalEmpire/perl5i/issues) or make a fork (forking on github is like a branch you control) and implement it yourself. Rationale Changing perl 5 core is a slow and difficult process. Perl 5 aims to be compatible with ancient versions which means it is mostly stuck with design, decisions and defaults made way back in the 90's. There are modules in CPAN to solve or ease many of those issues but many people don't know about them or don't know which ones to use. Documentation and books are updated slowly and don't usually keep up; this information becomes some sort of community knowledge, invisible from the wider audience. Even if you know a solution, having to decide everytime which module to use and enable it individually might be enough for you to give up and just do things the old way. Perl5i brings all this community knowledge in a coherent way, in something like 'the best of CPAN', enabled with a single command. You don't need to know all it does nor how it does it, you just use perl5i::2 on your code and you automatically get a modern environment, with perl defaults, problems and inconsistencies fixed. You can refer beginers to perl5i and they can benefit from it without needing to become a perl guru first. Using perl5i Because perl5i plans to be incompatible in the future, you do not simply use perl5i. You must declare which major version of perl5i you are using. You do this like so: # Use perl5i major version 2 use perl5i::2; Thus the code you write with, for example, perl5i::2 will always remain compatible even as perl5i moves on. If you want to be daring, you can use perl5i::latest to get the latest version. This will automatically happen if the program is -e. This lets you do slightly less typing for one-liners like perl -Mperl5i -e ... If you want your module to depend on perl5i, you should depend on the versioned class. For example, depend on perl5i::2 and not perl5i. See "VERSIONING" for more information about perl5i's versioning scheme. What it does perl5i enables each of these modules and adds/changes these functions. We'll provide a brief description here, but you should look at each of their documentation for full details. The Meta Object Every object (and everything is an object) now has a meta object associated with it. Using the meta object you can ask things about the object which were previously over complicated. For example... # the object's class my $class = $obj->mo->class; # its parent classes my @isa = $obj->mo->isa; # the complete inheritance hierarchy my @complete_isa = $obj->mo->linear_isa; # the reference type of the object my $reftype = $obj->mo->reftype; A meta object is used to avoid polluting the global method space. mo was chosen to avoid clashing with Moose's meta object. See perl5i::Meta for complete details. Subroutine and Method Signatures perl5i makes it easier to declare what parameters a subroutine takes. func hello($place) { say "Hello, $place!\n"; } method get($key) { return $self->{$key}; } method new($class: %args) { return bless \%args, $class; } func and method define subroutines as sub does, with some extra conveniences. The signature syntax is currently very simple. The content will be assigned from @_. This: func add($this, $that) { return $this + $that; } is equivalent to: sub add { my($this, $that) = @_; return $this + $that; } method defines a method. This is the same as a subroutine, but the first argument, the invocant, will be removed and made into $self. method get($key) { return $self->{$key}; } sub get { my $self = shift; my($key) = @_; return $self->{$key}; } Methods have a special bit of syntax. If the first item in the signature is $var: it will change the variable used to store the invocant. method new($class: %args) { return bless \%args, $class; } is equivalent to: sub new { my $class = shift; my %args = @_; return bless \%args, $class; } Anonymous functions and methods work, too. my $code = func($message) { say $message }; Guarantees include: @_ will not be modified except by removing the invocant Future versions of perl5i will add to the signature syntax and capabilities. Planned expansions include: Signature validation Signature documentation Named parameters Required parameters Read only parameters Aliased parameters Anonymous method and function declaration Variable method and function names Parameter traits Traditional prototypes See http://github.com/evalEmpire/perl5i/issues/labels/syntax#issue/19 for more details about future expansions. The equivalencies above should only be taken for illustrative purposes, they are not guaranteed to be literally equivalent. Note that while all parameters are optional by default, the number of parameters will eventually be enforced. For example, right now this will work: func add($this, $that) { return $this + $that } say add(1,2,3); # says 3 The extra argument is ignored. In future versions of perl5i this will be a runtime error. Signature Introspection The signature of a subroutine defined with func or method can be queried by calling the signature method on the code reference. func hello($greeting, $place) { say "$greeting, $place" } my $code = \&hello; say $code->signature->num_positional_params; # prints 2 Functions defined with sub will not have a signature. See perl5i::Signature for more details. Autoboxing autobox allows methods to be defined for and called on most unblessed variables. This means you can call methods on ordinary strings, lists and hashes! It also means perl5i can add a lot of functionality without polluting the global namespace. autobox::Core wraps a lot of Perl's built in functions so they can be called as methods on unblessed variables. @a->pop for example. alias $scalar_reference->alias( @identifiers ); @alias->alias( @identifiers ); %hash->alias( @identifiers ); (\&code)->alias( @identifiers ); Aliases a variable to a new global name. my $code = sub { 42 }; $code->alias( "foo" ); say foo(); # prints 42 It will work on everything except scalar references. our %stuff; %other_hash->alias( "stuff" ); # %stuff now aliased to %other_hash It is not a copy, changes to one will change the other. my %things = (foo => 23); our %stuff; %things->alias( "stuff" ); # alias %things to %stuff $stuff{foo} = 42; # change %stuff say $things{foo}; # and it will show up in %things Multiple @identifiers will be joined with '::' and used as the fully qualified name for the alias. my $class = "Some::Class"; my $name = "foo"; sub { 99 }->alias( $class, $name ); say Some::Class->foo; # prints 99 If there is just one @identifier and it has no "::" in it, the current caller will be prepended. $thing->alias("name") is shorthand for $thing->alias(CLASS, "name") Due to limitations in autobox, non-reference scalars cannot be aliased. Alias a scalar ref instead. my $thing = 23; $thing->alias("foo"); # error my $thing = \23; $thing->alias("foo"); # $foo is now aliased to $thing This is basically a nicer way to say: no strict 'refs'; *{$package . '::'. $name} = $reference; Scalar Autoboxing All of the methods provided by autobox::Core are available from perl5i. in addition, perl5i adds some methods of its own. path my $object = $path->path; Creates a Path::Tiny $object for the given file or directory $path. my $path = "/foo/bar/baz.txt"->path; my $content = $path->slurp; center my $centered_string = $string->center($length); my $centered_string = $string->center($length, $character); Centers $string between $character. $centered_string will be of length $length. $character defaults to " ". say "Hello"->center(10); # " Hello "; say "Hello"->center(10, '-'); # "---Hello--"; center() will never truncate $string. If $length is less than $string->length it will just return $string. say "Hello"->center(4); # "Hello"; round my $rounded_number = $number->round; Round to the nearest integer. round_up ceil my $new_number = $number->round_up; Rounds the $number towards infinity. 2.45->round_up; # 3 (-2.45)->round_up; # -2 ceil() is a synonym for round_up(). round_down floor my $new_number = $number->round_down; Rounds the $number towards negative infinity. 2.45->round_down; # 2 (-2.45)->round_down; # -3 floor() is a synonyn for round_down(). is_number $is_a_number = $thing->is_number; Returns true if $thing is a number understood by Perl. 12.34->is_number; # true "12.34"->is_number; # also true "eleven"->is_number; # false is_positive $is_positive = $thing->is_positive; Returns true if $thing is a positive number. 0 is not positive. is_negative $is_negative = $thing->is_negative; Returns true if $thing is a negative number. 0 is not negative. is_even $is_even = $thing->is_even; Returns true if $thing is an even integer. is_odd $is_odd = $thing->is_odd; Returns true if $thing is an odd integer. is_integer $is_an_integer = $thing->is_integer; Returns true if $thing is an integer. 12->is_integer; # true 12.34->is_integer; # false "eleven"->is_integer; # false is_int A synonym for is_integer is_decimal $is_a_decimal_number = $thing->is_decimal; Returns true if $thing is a decimal number. 12->is_decimal; # false 12.34->is_decimal; # true ".34"->is_decimal; # true "point five"->is_decimal; # false require my $module = $module->require; Will require the given $module. This avoids funny things like eval qq[require $module] or die $@. It accepts only module names. On failure it will throw an exception, just like require. On a success it returns the $module. This is mostly useful so that you can immediately call $module's import method to emulate a use. # like "use $module qw(foo bar);" if that worked $module->require->import(qw(foo bar)); # like "use $module;" if that worked $module->require->import; wrap my $wrapped = $string->wrap( width => $cols, separator => $sep ); Wraps $string to width $cols, breaking lines at word boundries using separator $sep. If no width is given, $cols defaults to 76. Default line separator is the newline character "\n". See Text::Wrap for details. ltrim rtrim trim my $trimmed = $string->trim; my $trimmed = $string->trim($character_set); Trim whitespace. ltrim() trims off the start of the string (left), rtrim() off the end (right) and trim() off both the start and end. my $string = ' testme'->ltrim; # 'testme' my $string = 'testme '->rtrim; # 'testme' my $string = ' testme '->trim; # 'testme' They all take an optional $character_set which will determine what characters should be trimmed. It follows regex character set syntax so A-Z will trim everything from A to Z. Defaults to \s, whitespace. my $string = '-> test <-'->trim('-><'); # ' test ' title_case my $name = 'joe smith'->title_case; # Joe Smith Will uppercase every word character that follows a wordbreak character. path2module my $module = $path->path2module; Given a relative $path it will return the Perl module this represents. For example, "Foo/Bar.pm"->path2module; # "Foo::Bar" It will throw an exception if given something which could not be a path to a Perl module. module2path my $path = $module->module2path; Will return the relative $path in which the Perl $module can be found. For example, "Foo::Bar"->module2path; # "Foo/Bar.pm" is_module_name my $is_valid = $string->is_module_name; Will return true if the $string is a valid module name. "Foo::Bar"->is_module_name; # true "Foo/Bar"->is_module_name; # false group_digits my $number_grouped = $number->group_digits; my $number_grouped = $number->group_digits(\%options); Turns a number like 1234567 into a string like 1,234,567 known as "digit grouping". It honors your current locale to determine the separator and grouping. This can be overridden using %options. NOTE: many systems do not have their numeric locales set properly separator The character used to separate groups. Defaults to "thousands_sep" in your locale or "," if your locale doesn't specify. decimal_point The decimal point character. Defaults to "decimal_point" in your locale or "." if your locale does not specify. grouping How many numbers in a group? Defaults to "grouping" in your locale or 3 if your locale doesn't specify. Note: we don't honor the full grouping locale, its a wee bit too complicated. currency If true, it will treat the number as currency and use the monetary locale settings. "mon_thousands_sep" instead of "thousands_sep" and "mon_grouping" instead of "grouping". 1234->group_digits; # 1,234 (assuming US locale) 1234->group_digits( separator => "." ); # 1.234 commify my $number_grouped = $number->commify; my $number_grouped = $number->commify(\%options); commify() is just like group_digits() but it is not locale aware. It is useful when you want a predictable result regardless of the user's locale settings. %options defaults to ( separator => ",", grouping => 3, decimal_point => "." ). Each key will be overridden individually. 1234->commify; # 1,234 1234->commify({ separator => "." }); # 1.234 reverse my $reverse = $string->reverse; Reverses a $string. Unlike Perl's reverse(), this always reverses the string regardless of context. Array Autoboxing The methods provided by "Array Methods" in autobox::Core are available from perl5i. All the functions from List::Util and select ones from List::MoreUtils are all available as methods on unblessed arrays and array refs: first, max, maxstr, min, minstr, minmax, shuffle, reduce, sum, any, all, none, true, false, uniq and mesh. They have all been altered to return array refs where applicable in order to allow chaining. @array->grep(sub{ $_->is_number })->sum->say; foreach @array->foreach( func($item) { ... } ); Works like the built in foreach, calls the code block for each element of @array passing it into the block. @array->foreach( func($item) { say $item } ); # print each item It will pass in as many elements as the code block accepts. This allows you to iterate through an array 2 at a time, or 3 or 4 or whatever. my @names = ("Joe", "Smith", "Jim", "Dandy", "Jane", "Lane"); @names->foreach( func($fname, $lname) { say "Person: $fname $lname"; }); A normal subroutine with no signature will get one at a time. If @array is not a multiple of the iteration (for example, @array has 5 elements and you ask 2 at a time) the behavior is currently undefined. as_hash my %hash = @array->as_hash; This method returns a %hash where each element of @array is a key. The values are all true. Its functionality is similar to: my %hash = map { $_ => 1 } @array; Example usage: my @array = ("a", "b", "c"); my %hash = @array->as_hash; say q[@array contains 'a'] if $hash{"a"}; pick my @rand = @array->pick($number); The pick() method returns a list of $number elements in @array. If $number is larger than the size of the list, it returns the entire list shuffled. Example usage: my @array = (1, 2, 3, 4); my @rand = @array->pick(2); pick_one my $rand = @array->pick_one; The pick_one() method returns a random element in @array. It is similar to @array->pick(1), except that it does not return a list. Example usage: my @array = (1,2,3,4); my $rand = @array->pick_one; diff Calculate the difference between two (or more) arrays: my @a = ( 1, 2, 3 ); my @b = ( 3, 4, 5 ); my @diff_a = @a->diff(\@b) # [ 1, 2 ] my @diff_b = @b->diff(\@a) # [ 4, 5 ] Diff returns all elements in array @a that are not present in array @b. Item order is not considered: two identical elements in both arrays will be recognized as such disregarding their index. [ qw( foo bar ) ]->diff( [ qw( bar foo ) ] ) # empty, they are equal For comparing more than two arrays: @a->diff(\@b, \@c, ... ) All comparisons are against the base array (@a in this example). The result will be composed of all those elements that were present in @a and in none other. It also works with nested data structures; it will traverse them depth-first to assess whether they are identical or not. For instance: [ [ 'foo ' ], { bar => 1 } ]->diff([ 'foo' ]) # [ { bar => 1 } ] In the case of overloaded objects (i.e., DateTime, URI, Path::Class, etc.), it tries its best to treat them as strings or numbers. my $uri = URI->new("http://www.perl.com"); my $uri2 = URI->new("http://www.perl.com"); [ $uri ]->diff( [ "http://www.perl.com" ] ); # empty, they are equal [ $uri ]->diff( [ $uri2 ] ); # empty, they are equal popn my @newarray = @array->popn($n); Pops $n values from the @array. If $n is greater than the length of @array, it will return the whole @array. If $n is 0, it will return an empty array. A negative $n or non-integer is an error. my @array = (1, 2, 3, 4, 5); my @newarray = @array->popn(3); # (3, 4, 5) shiftn my @newarray = @array->shiftn($n); Works like popn, but it shifts off the front of the array instead of popping off the end. my @array = (1, 2, 3, 4, 5); my @newarray = @array->shiftn(3); # (1, 2, 3) intersect my @a = (1 .. 10); my @b = (5 .. 15); my @intersection = @a->intersect(\@b) # [ 5 .. 10 ]; Performs intersection between arrays, returning those elements that are present in all of the argument arrays simultaneously. As with diff(), it works with any number of arrays, nested data structures of arbitrary depth, and handles overloaded objects graciously. ltrim rtrim trim my @trimmed = @list->trim; my @trimmed = @list->trim($character_set); Trim whitespace from each element of an array. Each works just like their scalar counterpart. my @trimmed = [ ' foo', 'bar ' ]->ltrim; # [ 'foo', 'bar ' ] my @trimmed = [ ' foo', 'bar ' ]->rtrim; # [ ' foo', 'bar' ] my @trimmed = [ ' foo', 'bar ' ]->trim; # [ 'foo', 'bar' ] As with the scalar trim() methods, they all take an optional $character_set which will determine what characters should be trimmed. my @trimmed = ['-> foo <-', '-> bar <-']->trim('-><'); # [' foo ', ' bar '] Hash Autoboxing All of the methods provided by "Hash Methods" in autobox::Core are available from perl5i. In addition... each Iterate through each key/value pair in a hash using a callback. my %things = ( foo => 23, bar => 42 ); %things->each( func($k, $v) { say "Key: $k, Value: $v" }); Unlike the each function, individual calls to each are guaranteed to iterate through the entirety of the hash. flip Exchanges values for keys in a hash. my %things = ( foo => 1, bar => 2, baz => 5 ); my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz } If there is more than one occurrence of a certain value, any one of the keys may end up as the value. This is because of the random ordering of hash keys. # Could be { 1 => foo }, { 1 => bar }, or { 1 => baz } { foo => 1, bar => 1, baz => 1 }->flip; Because hash references cannot usefully be keys, it will not work on nested hashes. { foo => [ 'bar', 'baz' ] }->flip; # dies merge Recursively merge two or more hashes together using Hash::Merge::Simple. my $a = { a => 1 }; my $b = { b => 2, c => 3 }; $a->merge($b); # { a => 1, b => 2, c => 3 } For conflicting keys, rightmost precedence is used: my $a = { a => 1 }; my $b = { a => 100, b => 2}; $a->merge($b); # { a => 100, b => 2 } $b->merge($a); # { a => 1, b => 2 } It also works with nested hashes, although it won't attempt to merge array references or objects. For more information, look at the Hash::Merge::Simple docs. diff my %staff = ( bob => 42, martha => 35, timmy => 23 ); my %promoted = ( timmy => 23 ); %staff->diff(\%promoted); # { bob => 42, martha => 35 } Returns the key/value pairs present in the first hash that are not present in the subsequent hash arguments. Otherwise works as @array->diff. intersect %staff->intersect(\%promoted); # { timmy => 23 } Returns the key/value pairs that are present simultaneously in all the hash arguments. Otherwise works as @array->intersect. Code autoboxing signature my $sig = $code->signature; You can query the signature of any code reference defined with func or method. See "Signature Introspection" for details. If $code has a signature, returns an object representing $code's signature. See perl5i::Signature for details. Otherwise it returns nothing. caller Perl6::Caller causes caller to return an object in scalar context. die die now always returns an exit code of 255 instead of trying to use $! or $? which makes the exit code unpredictable. If you want to exit with a message and a special exit code, use warn then exit. list list will force list context similar to how scalar will force scalar context. utf8::all perl5i turns on utf8::all which turns on all the Unicode features of Perl it can. Here is the current list, more may be turned on later. Bare strings in your source code are now UTF8. This means UTF8 variable and method names, strings and regexes. my $message = "انا لا اتكلم العربيه"; my $τάδε = "It's all Greek to me!"; sub fünkßhüñ { ... } Strings will be treated as a set of characters rather than a set of bytes. For example, length will return the number of characters, not the number of bytes. length("perl5i is MËTÁŁ"); # 15, not 18 @ARGV will be read as UTF8. STDOUT, STDIN, STDERR and all newly opened filehandles will have UTF8 encoding turned on. Consequently, if you want to output raw bytes to a file, such as outputting an image, you must set binmode $fh. capture my($stdout, $stderr) = capture { ... } %options; my $stdout = capture { ... } %options; capture() lets you capture all output to STDOUT and STDERR in any block of code. # $out = "Hello" # $err = "Bye" my($out, $err) = capture { print "Hello"; print STDERR "Bye"; }; If called in scalar context, it will only return STDOUT and silence STDERR. # $out = "Hello" my $out = capture { print "Hello"; warn "oh god"; }; capture takes some options. tee tee will cause output to be captured yet still printed. my $out = capture { print "Hi" } tee => 1; merge merge will merge STDOUT and STDERR into one variable. # $out = "HiBye" my $out = capture { print "Hi"; print STDERR "Bye"; } merge => 1; Carp croak and carp from Carp are always available. The Carp message will always format consistently, smoothing over the backwards incompatible change in Carp 1.25. Child Child provides the child function which is a better way to do forking. child creates and starts a child process, and returns an Child::Link::Proc object which is a better interface for managing the child process. The only required argument is a codeblock, which is called in the new process. exit() is automatically called for you after the codeblock returns. my $proc = child { my $parent = shift; ... }; You can also request a pipe for IPC: my $proc = child { my $parent = shift; $parent->say("Message"); my $reply = $parent->read(); ... } pipe => 1; my $message = $proc->read(); $proc->say("reply"); See Child for more information. English English gives English names to the punctuation variables; for instance, <$@> is also <$EVAL_ERROR>. See perlvar for details. It does not load the regex variables which affect performance. $PREMATCH, $MATCH, and $POSTMATCH will not exist. See the p modifier in perlre for a better alternative. Modern::Perl Modern::Perl turns on strict and warnings, enables all the 5.10 features like given/when, say and state, and enables C3 method resolution order. CLASS Provides CLASS and $CLASS alternatives to __PACKAGE__. File::chdir File::chdir gives you $CWD representing the current working directory and it's assignable to chdir. You can also localize it to safely chdir inside a scope. File::stat File::stat causes stat to return an object in scalar context. DateTime time, localtime, and gmtime are replaced with DateTime objects. They will all act like the core functions. # Sat Jan 10 13:37:04 2004 say scalar gmtime(2**30); # 2004 say gmtime(2**30)->year; # 2009 (when this was written) say time->year; Time::y2038 gmtime() and localtime() will now safely work with dates beyond the year 2038 and before 1901. The exact range is not defined, but we guarantee at least up to 2**47 and back to year 1. IO::Handle Turns filehandles into objects so you can call methods on them. The biggest one is autoflush rather than mucking around with $| and select. $fh->autoflush(1); autodie autodie causes system and file calls which can fail (open, system, and chdir, for example) to die when they fail. This means you don't have to put or die at the end of every system call, but you do have to wrap it in an eval block if you want to trap the failure. autodie's default error messages are pretty smart. All of autodie will be turned on. autovivification autovivification fixes the bug/feature where this: $hash = {}; $hash->{key1}{key2}; Results in $hash->{key1} coming into existence. That will no longer happen. No indirect object syntax perl5i turns indirect object syntax, ie. new $obj, into a compile time error. Indirect object syntax is largely unnecessary and removing it avoids a number of ambiguous cases where Perl will mistakenly try to turn a function call into an indirect method call. See indirect for details. want want() generalizes the mechanism of the wantarray function, allowing a function to determine the context it's being called in. Want distinguishes not just scalar v. array context, but void, lvalue, rvalue, boolean, reference context, and more. See perldoc Want for full details. Try::Tiny Try::Tiny gives support for try/catch blocks as an alternative to eval BLOCK. This allows correct error handling with proper localization of $@ and a nice syntax layer: # handle errors with a catch handler try { die "foo"; } catch { warn "caught error: $_"; }; # just silence errors try { die "foo"; }; See perldoc Try::Tiny for details. true You no longer have to put a true value at the end of a module which uses perl5i. Better load errors Most of us have learned the meaning of the dreaded "Can't locate Foo.pm in @INC". Admittedly though, it's not the most helpful of the error messages. In perl5i we provide a much friendlier error message. Example: Can't locate My/Module.pm in your Perl library. You may need to install it from CPAN or another repository. Your library paths are: Indented list of paths, 1 per line... Turning off features use perl5i::2 -skip => \@features_to_skip; While perl5i is intended as a curated collection of modules, its possible you might not want certain features. Features can be turned off in your scope by using -skip. For example, this will skip loading Try::Tiny. use perl5i::latest -skip => [qw(Try::Tiny)]; Why would you do this? You might want to use a different try/catch module such as TryCatch which provides its own try and catch. The feature strings are: autobox, autodie, autovivification, capture, Carp::Fix::1_25, Child, CLASS, die, English, File::chdir, indirect, list, Meta, Modern::Perl, Perl6::Caller, Signatures, stat, time, true, Try::Tiny, utf8::all, Want. Command line program There is a perl5i command line program installed with perl5i (Windows users get perl5i.bat). This is handy for writing one liners. perl5i -e 'gmtime->year->say' And you can use it on the #! line. #!/usr/bin/perl5i gmtime->year->say; If you write a one-liner without using this program, saying -Mperl5i means -Mperl5i::latest. Please see "Using perl5i" and "VERSIONING" for details. BUGS Some parts are not lexical. Some parts are package scoped. If you're going to use two versions of perl5i together, we do not currently recommend having them in the same package. See http://github.com/evalEmpire/perl5i/issues/labels/bug for a complete list. Please report bugs at http://github.com/evalEmpire/perl5i/issues/. VERSIONING perl5i follows the Semantic Versioning policy, http://semver.org. In short... Versions will be of the form X.Y.Z. 0.Y.Z may change anything at any time. Incrementing X (ie. 1.2.3 -> 2.0.0) indicates a backwards incompatible change. Incrementing Y (ie. 1.2.3 -> 1.3.0) indicates a new feature. Incrementing Z (ie. 1.2.3 -> 1.2.4) indicates a bug fix or other internal change. NOTES Inspired by chromatic's Modern::Perl and in particular http://www.modernperlbooks.com/mt/2009/04/ugly-perl-a-lesson-in-the-importance-of-language-design.html. I totally didn't come up with the "Perl 5 + i" joke. I think it was Damian Conway. THANKS Thanks to our contributors: Chas Owens, Darian Patrick, rjbs, chromatic, Ben Hengst, Bruno Vecchi and anyone else I've forgotten. Thanks to Flavian and Matt Trout for their signature and Devel::Declare work. Thanks to all the CPAN authors upon whom this builds. LICENSE Copyright 2009-2010, Michael G Schwern <[email protected]> This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://dev.perl.org/licenses/artistic.html SEE ALSO Repository: http://github.com/evalEmpire/perl5i/ Issues/Bugs: http://github.com/evalEmpire/perl5i/issues IRC: irc://irc.perl.org on the #perl5i channel Wiki: http://github.com/evalEmpire/perl5i/wiki Twitter: http://twitter.com/perl5i Frequently Asked Questions about perl5i: perl5ifaq Some modules with similar purposes include: Modern::Perl, Common::Sense For a complete object declaration system, see Moose and MooseX::Declare.
Something to make changing directory lexical.
File::chdir? File::pushd?
Might it be handy to load that? Maybe make %RE load Regexp::Common on demand.
Like in Ruby.
@foo = map { |$var| $var++ } @bar;
to be equivalent to
@foo = map { $_++ } @bar;
Perhaps using Data::Bind?
Much of perl5i is not lexical. Muck with %^H to make it so. Tests in t/lexical.t
Now that we have autobox, add in a method to dump any variable. autobox::Core may already have this.
And they don't warn!
$ time perl -wle 'use perl5i; print scalar gmtime 2**48-2**46-2**45+2**44-2**43+2**42-2**41-2**40'
Mon Jan 3 06:09:04 -5868930
$ time perl -wle 'use perl5i; print scalar gmtime 2**48-2**46-2**45+2**44-2**43+2**42-2**41-2**40-2**39'
Sat Dec 28 17:50:56 5872869
The bin/perl5i.PL script currently generates a *nix sell script that invokes perl with perl5i niceties. Something similar is needed for Windows, likely using a .bat file or something. Schwern mentioned pl2bat from Module::Build as a possible solution.
http://www.rubycentral.com/pickaxe/ref_c_string.html#String.center
$word = "Hello";
$word->center(20) = " hello ";
Add something to smooth out cross platform issues with running programs.
IPC::Cmd? IPC::Run?
Document the existence of the perl5i utility in the module and also provide some POD in the thing itself.
touch
recursive rm
mv and cp allowing multiple source files to a directory
mkdir -p
Crib from ExtUtils::Command and Shell::Command.
Time::y2038 doesn't play nice with Time::Piece. They both want to override localtime and gmtime. Worse, Time::Piece will use CORE::localtime and CORE::gmtime so it won't see Time::y2038.
All that getpwuid and junk.
Somehow integrate local::lib to solve the problem of locally installed modules
Would it be helpful to automatically use mylib to have an absolute path to /path/which/contains/program/lib ?
force anything in to list context
eq_or_diff( [flat([[{this =>{is => [qw{a test}]}}])], [qw{this is a test}] )
To allow chaining
It might be a good idea to have a source filter to change
local @CWD;
into
local $CWD;
or at least throw a warning.
File::stat will cause stat() to always return an object. It should be trivial to make it return the traditional list of stuff in array context, or to overload the object. This will make it backwards compatible.
I don't know if this is a bug in perl5i or the modules it uses, but I needed to install the following modules to get the tests to pass (even though perl Build.PL said everything was okay):
Time-Piece.t - IPC::System::Simple
Module-Load.t - Text::ParseWords
modern-perl.t - Array::Compare
Uppercase each word in a string.
Like stat() and localtime()
We needs some. Carp is the obvious choice. Is there a better one?
MooseX::Declare is sexy. It also solves the problem of Moose load time since it can lazy load when class() is called.
This thing is going to get pretty fat pretty fast. It would be nice if it delayed loading of modules for as long as possible.
Things like File::stat and Time::Piece that only export a handful of functions can be wrapped in autoloading functions. Just benchmark before hand to see if it helps load time to actually remove them. A lot of the cost of loading a module in isolation is actually loading very common modules (strict, Exporter, base...) which will be loaded anyway.
Instead of
no strict 'refs';
*{$package .'::'. $name} = sub { ... };
write
alias( $package .'::'. $name, sub { ... } );
Though some of the method names could use some work. Like natatime().
uniq, zip, any, all, none, true, false are all nice.
The latest version of DateTime in CPAN is 0.47, but you are requiring 1.12.
One pain I have seen people have is the lack of a trim function. I have seen numerous CompanyName::Util modules with weird/bad/ugly trim functions. The problem with trim though is its lack of definition: should it trim on the left, on the right, or both; should it trim spaces, whitespace, or custom character classe; should it modify the string or return a copy; etc. Normally the right answer (in my opinion) is to use a substitution written for that specific case, but people seem resistant to that (and they do have some good arguments). I think we should provide a scalar trim method with the following arguments:
is "\tfoo "->trim, "foo", "default removes whitespace on both sides, does not modify string";
is "\tfoo "->trim(" "), "\tfoo", "sinlge arg is character to remove";
is "\tfoo "->trim("[f \t]"), "oo", "single arg can be a character class";
is "\tfoo "->trim('\s'), "foo", "sinlge arg can be a shorthand character class";
is "\tfoo "->trim(left => '\s'), "foo ", "multiple args are a named paramters, in this case trim on the left";
is "\tfoo "->ltrim, "foo ", "trim on the left (TIMTOWTDI);
not_ok eval { "\tfoo "->ltrim(right => '\s'); 1 }, "left trim croaks if asked to trim on the right";
is $@, "probable misuse of ltrim", "ltrim croaks with this error message";
not_ok eval { "\tfoo "->trim(both => '\s'); 1 }, "left trim croaks if asked to trim both";
is $@, "probable misuse of ltrim", "ltrim croaks with this error message";
is "\tfoo "->trim(right => '\s'), "\tfoo", "trim on the right";
is "\tfoo "->rtrim, "\tfoo", "trim on the right ("TIMTOWTDI");
not_ok eval { "\tfoo "->rtrim(left => '\s'); 1 }, "right trim croaks if asked to trim on the left";
is $@, "probable misuse of rtrim", "rtrim croaks with this error message";
not_ok eval { "\tfoo "->trim(both => '\s'); 1 }, "right trim croaks if asked to trim both";
is $@, "probable misuse of ltrim", "rtrim croaks with this error message";
is "\tfoo "->trim(both => '\s'), "foo", "trim on both";
is "\tfoo "->trim(left => '\s', right => '\s'), "foo", "trim on both (TIMTOWTDI)";
my $foo = "\tfoo ";
is $foo->(inplace => 'true'), "foo", "if left, right, or both is not set default to both";
is $foo, "foo", "inplace attempts to change the scalar";
not_ok eval { "\tfoo "->trim(inplace => 1); 1 }, "inplace croaks if it can't modify the string";
ok $@ =~ qr/trim could not modify scalar/, "it croaks with this error message";
Incorporate subroutine and method signatures.
Rather than having to muck with File::Spec.
Path::Class?
alias my $foo => \$bar;
would be spiffy. Data::Alias would do that, but its kinda broken on bleadperl.
It looks like the slowness is in DateTime->set_time_zone(). It starts to get noticeably slower after 2038.
I hate typing use Data::Dumper; warn Dumper [ $foo ].
Optionally, rename it to dump().
Use DateTime instead of Time::Piece. Write gmtime() and localtime() to return DateTime objects which stringify to emulate ctime. This may eliminate the need for Time::y2038.
trim (strip whitespace), ltrim, rtrim
is a number
is an integer, decimal... all the stuff from perlfaq4
is a regex
is an object/instance
is a reference
Wrap to X columns. use Text::Wrap
Instead of
for my $key (keys %hash) {
my $value = $hash{$key};
....
}
I want
for my($key, $value) (%hash) {
...
}
Or something. Also working for pairs in lists. Extend it out to work for any number of elements.
Stuff for merging hashes and flattening hashes.
I think you mean File::Stat? Not sure what version you want.
Like in Ruby.
read $file {
print;
}
Use an overloaded object which boolifies to true/false but numifies to the exit code. This will let if( system("...") ) work but also let if( system("...") == 0 ) still work.
And they don't warn!
$ time perl -wle 'use perl5i; print scalar gmtime 248-246-245+244-243+242-241-240'
Mon Jan 3 06:09:04 -5868930
$ time perl -wle 'use perl5i; print scalar gmtime 248-246-245+244-243+242-241-240-2**39'
Sat Dec 28 17:50:56 5872869
File::Slurp is the obvious candidate. I also like that it can write_file() in one go.
Perl6::Slurp is far more complete, but it doesn't write files, its way more complicated and its scary, old, unmaintained Damian-ware. Perhaps the solution is to enhance File::Slurp with Perl6::Slurp features.
Finally, a solution to the "how do I insert a line in the middle of a file" would be nice. That can be served by the excellent and efficient Tie::File but with a sprinkling of sugar so the user isn't exposed to a tie() call. They just get an array (or array ref or object acting like an array ref).
Jesse Wolfe is annoyed that he can't put objects/references in hash keys. I don't know if there's a way to do this without patching core, but it sure would be nice
An improved configuration for the CPAN shell. It will ask one question "do you want to install for yourself or for the whole system" and then configure everything for you. Then it will ask "do you want detailed configuration?" with a default of "no". That's it. You will have a working, configured CPAN shell.
The datetime.t test seems to be missing from the repository.
Pull it from Algorithm::Numeric::Shuffle. People screw up shuffling all the time.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.