| 1 |
NAME |
| 2 |
autobox::Core - Provide core functions to autoboxed scalars, arrays and |
| 3 |
hashes. |
| 4 |
|
| 5 |
SYNOPSIS |
| 6 |
use autobox::Core; |
| 7 |
|
| 8 |
"Hello, World\n"->uc->print; |
| 9 |
|
| 10 |
my @list = (1, 5, 9, 2, 0, 4, 2, 1); |
| 11 |
@list->sort->reverse->print; |
| 12 |
|
| 13 |
# works with references too! |
| 14 |
my $list = [1, 5, 9, 2, 0, 4, 2, 1]; |
| 15 |
$list->sort->reverse->print; |
| 16 |
|
| 17 |
my %hash = ( |
| 18 |
grass => 'green', |
| 19 |
apple => 'red', |
| 20 |
sky => 'blue', |
| 21 |
); |
| 22 |
|
| 23 |
[10, 20, 30, 40, 50]->pop->say; |
| 24 |
[10, 20, 30, 40, 50]->shift->say; |
| 25 |
|
| 26 |
my $lala = "Lalalalala\n"; |
| 27 |
"chomp: "->concat($lala->chomp, " ", $lala)->say; |
| 28 |
|
| 29 |
my $hashref = { foo => 10, bar => 20, baz => 30, qux => 40 }; |
| 30 |
|
| 31 |
print "hash keys: ", $hashref->keys->join(' '), "\n"; # or if you prefer... |
| 32 |
print "hash keys: ", join ' ', $hashref->keys(), "\n"; # or |
| 33 |
print "hash keys: "; $hashref->keys->say; |
| 34 |
|
| 35 |
DESCRIPTION |
| 36 |
The autobox module promotes Perl's primitive types (literals (strings |
| 37 |
and numbers), scalars, arrays and hashes) into first-class objects. |
| 38 |
However, autobox does not provide any methods for these new classes. |
| 39 |
|
| 40 |
autobox::CORE provides a set of methods for these new classes. It |
| 41 |
includes almost everything in perlfunc, some things from Scalar::Util |
| 42 |
and List::Util, and some Perl 5 versions of methods taken from Perl 6. |
| 43 |
|
| 44 |
With autobox::Core one is able to change this: |
| 45 |
|
| 46 |
print join(" ", reverse(split(" ", $string))); |
| 47 |
|
| 48 |
to this: |
| 49 |
|
| 50 |
use autobox::Core; |
| 51 |
|
| 52 |
$string->split(" ")->reverse->print; |
| 53 |
|
| 54 |
Likewise you can change this: |
| 55 |
|
| 56 |
my $array_ref = [qw(fish dog cat elephant bird)]; |
| 57 |
|
| 58 |
push @$array_ref, qw(snake lizard giraffe mouse); |
| 59 |
|
| 60 |
to this: |
| 61 |
|
| 62 |
use autobox::Core; |
| 63 |
my $array_ref = [qw(fish dog cat elephant bird)]; |
| 64 |
|
| 65 |
$array_ref->push( qw(snake lizard giraffe mouse)); |
| 66 |
|
| 67 |
autobox::Core makes it easier to avoid parentheses pile ups and messy |
| 68 |
dereferencing syntaxes. |
| 69 |
|
| 70 |
autobox::Core is mostly glue. It presents existing functions with a new |
| 71 |
interface, while adding few extra. Most of the methods read like "sub |
| 72 |
hex { CORE::hex($_[0]) }". In addition to built-ins from perlfunc that |
| 73 |
operate on hashes, arrays, scalars, and code references, some Perl 6-ish |
| 74 |
things have been included, and some keywords like "foreach" are |
| 75 |
represented too. |
| 76 |
|
| 77 |
What's Implemented? |
| 78 |
* Many of the functions listed in perlfunc under the headings: |
| 79 |
|
| 80 |
* "Functions for real @ARRAYs", |
| 81 |
|
| 82 |
* "Functions for real %HASHes", |
| 83 |
|
| 84 |
* "Functions for list data", |
| 85 |
|
| 86 |
* "Functions for SCALARs or strings" |
| 87 |
|
| 88 |
plus a few taken from other sections and documented below. |
| 89 |
|
| 90 |
* Some methods from Scalar::Util and List::Util. |
| 91 |
|
| 92 |
* Some things expected in Perl 6, such as "last" ("last_idx"), |
| 93 |
"elems", and "curry". |
| 94 |
|
| 95 |
* "flatten" explicitly flattens an array. |
| 96 |
|
| 97 |
String Methods |
| 98 |
String methods are of the form "my $return = $string->method(@args)". |
| 99 |
Some will act on the $string and some will return a new string. |
| 100 |
|
| 101 |
Many string methods are simply wrappers around core functions, but there |
| 102 |
are additional operations and modifications to core behavior. |
| 103 |
|
| 104 |
Anything which takes a regular expression, such as split and m, usually |
| 105 |
take it in the form of a compiled regex ("qr//"). Any modifiers can be |
| 106 |
attached to the "qr" normally. Bare strings may be used in place of |
| 107 |
regular expressions, and Perl will compile it to a regex, as usual. |
| 108 |
|
| 109 |
These built in functions are implemented for scalars, they work just |
| 110 |
like normal: chomp, chop,chr crypt, index, lc lcfirst, length, ord, |
| 111 |
pack, reverse (always in scalar context), rindex, sprintf, substr, uc |
| 112 |
ucfirst, unpack, quotemeta, vec, undef, split, system, eval. |
| 113 |
|
| 114 |
In addition, so are each of the following: |
| 115 |
|
| 116 |
concat |
| 117 |
$string1->concat($string2); |
| 118 |
|
| 119 |
Concatenates $string2 to $string1. This corresponds to the "." operator |
| 120 |
used to join two strings. Returns the joined strings. |
| 121 |
|
| 122 |
strip |
| 123 |
Removes whitespace from the beginning and end of a string. |
| 124 |
|
| 125 |
" \t \n \t foo \t \n \t "->strip; # foo |
| 126 |
|
| 127 |
This is redundant and subtly different from "trim" which allows for the |
| 128 |
removal of specific characters from the beginning and end of a string. |
| 129 |
|
| 130 |
trim |
| 131 |
Removes whitespace from the beginning and end of a string. "trim" can |
| 132 |
also remove specific characters from the beginning and the end of |
| 133 |
string. |
| 134 |
|
| 135 |
' hello'->trim; # 'hello' |
| 136 |
'*+* hello *+*'->trim("*+"); # ' hello ' |
| 137 |
' *+* hello *+*'->trim("*+"); # ' *+* hello' |
| 138 |
|
| 139 |
ltrim |
| 140 |
Just like trim but it only trims the left side (start) of the string. |
| 141 |
|
| 142 |
' hello'->ltrim; # 'hello' |
| 143 |
'*+* hello *+*'->ltrim("*+"); # ' hello *+*' |
| 144 |
|
| 145 |
rtrim |
| 146 |
Just like trim but it only trims the right side (end) of the string. |
| 147 |
|
| 148 |
'hello '->rtrim; # 'hello' |
| 149 |
'*+* hello *+*'->rtrim("*+"); # '*+* hello ' |
| 150 |
|
| 151 |
split |
| 152 |
my @split_string = $string->split(qr/.../); |
| 153 |
my @split_string = $string->split(' '); |
| 154 |
|
| 155 |
A wrapper around split. It takes the regular expression as a compiled |
| 156 |
regex, or a string which Perl parses as a regex. |
| 157 |
|
| 158 |
print "10, 20, 30, 40"->split(qr{, ?})->elements, "\n"; |
| 159 |
"hi there"->split(qr/ */); # h i t h e r e |
| 160 |
|
| 161 |
The limit argument is not implemented. |
| 162 |
|
| 163 |
title_case |
| 164 |
"title_case" converts the first character of each word in the string to |
| 165 |
upper case. |
| 166 |
|
| 167 |
"this is a test"->title_case; # This Is A Test |
| 168 |
|
| 169 |
center |
| 170 |
my $centered_string = $string->center($length); |
| 171 |
my $centered_string = $string->center($length, $character); |
| 172 |
|
| 173 |
Centers $string between $character. $centered_string will be of length |
| 174 |
$length, or the length of $string, whichever is greater. |
| 175 |
|
| 176 |
$character defaults to " ". |
| 177 |
|
| 178 |
say "Hello"->center(10); # " Hello "; |
| 179 |
say "Hello"->center(10, '-'); # "---Hello--"; |
| 180 |
|
| 181 |
"center()" will never truncate $string. If $length is less than |
| 182 |
"$string->length" it will just return $string. |
| 183 |
|
| 184 |
say "Hello"->center(4); # "Hello"; |
| 185 |
|
| 186 |
qx |
| 187 |
my $output = $string->qx; |
| 188 |
|
| 189 |
Runs $string as a command just enclosing it backticks, as in `$string`. |
| 190 |
|
| 191 |
nm |
| 192 |
if( $foo->nm(qr/bar/) ) { |
| 193 |
say "$foo did not match 'bar'"; |
| 194 |
} |
| 195 |
|
| 196 |
"Negative match". Corresponds to "!~". Otherwise works in the same way |
| 197 |
as "m()". |
| 198 |
|
| 199 |
m |
| 200 |
if( $foo->m(qr/bar/) ) { |
| 201 |
say "$foo matched 'bar'"; |
| 202 |
} |
| 203 |
|
| 204 |
my $matches = $foo->m( qr/(\d*) (\w+)/ ); |
| 205 |
say $matches->[0]; |
| 206 |
say $matches->[1]; |
| 207 |
|
| 208 |
Works the same as "m//", but the regex must be passed in as a "qr//". |
| 209 |
|
| 210 |
"m" returns an array reference so that list functions such as "map" and |
| 211 |
"grep" may be called on the result. Use "elements" to turn this into a |
| 212 |
list of values. |
| 213 |
|
| 214 |
my ($street_number, $street_name, $apartment_number) = |
| 215 |
"1234 Robin Drive #101"->m( qr{(\d+) (.*)(?: #(\d+))?} )->elements; |
| 216 |
|
| 217 |
print "$street_number $street_name $apartment_number\n"; |
| 218 |
|
| 219 |
s |
| 220 |
my $string = "the cat sat on the mat"; |
| 221 |
$string->s( qr/cat/, "dog" ); |
| 222 |
$string->say; # the dog sat on the mat |
| 223 |
|
| 224 |
String substitution. Works similarly to "s///". In boolean context, it |
| 225 |
returns true/false to indicate whether the substitution succeeded. "if", |
| 226 |
"?:", "!", and so on, all provide boolean context. It either fails or |
| 227 |
succeeds, having replaced only one occurrence on success -- it doesn't |
| 228 |
replace globally. In scalar context other than boolean context, it |
| 229 |
returns the modified string (incompatible change, new as of v 1.31). |
| 230 |
|
| 231 |
undef |
| 232 |
$string->undef; |
| 233 |
|
| 234 |
Assigns "undef" to the $string. |
| 235 |
|
| 236 |
defined |
| 237 |
my $is_defined = $string->defined; |
| 238 |
|
| 239 |
if( not $string->defined ) { |
| 240 |
# give $string a value... |
| 241 |
} |
| 242 |
|
| 243 |
"defined" tests whether a value is defined (not "undef"). |
| 244 |
|
| 245 |
repeat |
| 246 |
my $repeated_string = $string->repeat($n); |
| 247 |
|
| 248 |
Like the "x" operator, repeats a string $n times. |
| 249 |
|
| 250 |
print 1->repeat(5); # 11111 |
| 251 |
print "\n"->repeat(10); # ten newlines |
| 252 |
|
| 253 |
I/O Methods |
| 254 |
These are methods having to do with input and ouptut, not filehandles. |
| 255 |
|
| 256 |
print |
| 257 |
$string->print; |
| 258 |
|
| 259 |
Prints a string or a list of strings. Returns true if successful. |
| 260 |
|
| 261 |
say |
| 262 |
Like print, but implicitly appends a newline to the end. |
| 263 |
|
| 264 |
$string->say; |
| 265 |
|
| 266 |
Boolean Methods |
| 267 |
Methods related to boolean operations. |
| 268 |
|
| 269 |
and |
| 270 |
"and" corresponds to "&&". Returns true if both operands are true. |
| 271 |
|
| 272 |
if( $a->and($b) ) { |
| 273 |
... |
| 274 |
} |
| 275 |
|
| 276 |
not |
| 277 |
"not" corresponds to "!". Returns true if the subject is false. |
| 278 |
|
| 279 |
if( $a->not ) { |
| 280 |
... |
| 281 |
} |
| 282 |
|
| 283 |
or |
| 284 |
"or" corresponds to "||". Returns true if at least one of the operands |
| 285 |
is true. |
| 286 |
|
| 287 |
if( $a->or($b) ) { |
| 288 |
... |
| 289 |
} |
| 290 |
|
| 291 |
xor |
| 292 |
"xor" corresponds to "xor". Returns true if only one of the operands is |
| 293 |
true. |
| 294 |
|
| 295 |
if( $a->xor($b) ) { |
| 296 |
... |
| 297 |
} |
| 298 |
|
| 299 |
Number Related Methods |
| 300 |
Methods related to numbers. |
| 301 |
|
| 302 |
The basic built in functions which operate as normal : abs, atan2, cos, |
| 303 |
exp, int, log, oct, hex, sin, and sqrt. |
| 304 |
|
| 305 |
The following operators were also included: |
| 306 |
|
| 307 |
dec |
| 308 |
$number->dec(); |
| 309 |
# $number is smaller by 1. |
| 310 |
|
| 311 |
"dec" corresponds to "++". Decrements subject, will decrement character |
| 312 |
strings too: 'b' decrements to 'a'. |
| 313 |
|
| 314 |
inc |
| 315 |
"inc" corresponds to "++". Increments subject, will increment character |
| 316 |
strings too. 'a' increments to 'b'. |
| 317 |
|
| 318 |
mod |
| 319 |
"mod" corresponds to "%". |
| 320 |
|
| 321 |
$number->mod(5); |
| 322 |
|
| 323 |
pow |
| 324 |
"pow" returns $number raised to the power of the $exponent. |
| 325 |
|
| 326 |
my $result = $number->pow($expontent); |
| 327 |
print 2->pow(8); # 256 |
| 328 |
|
| 329 |
is_number |
| 330 |
$is_a_number = $thing->is_number; |
| 331 |
|
| 332 |
Returns true if $thing is a number as understood by Perl. |
| 333 |
|
| 334 |
12.34->is_number; # true |
| 335 |
"12.34"->is_number; # also true |
| 336 |
|
| 337 |
is_positive |
| 338 |
$is_positive = $thing->is_positive; |
| 339 |
|
| 340 |
Returns true if $thing is a positive number. |
| 341 |
|
| 342 |
0 is not positive. |
| 343 |
|
| 344 |
is_negative |
| 345 |
$is_negative = $thing->is_negative; |
| 346 |
|
| 347 |
Returns true if $thing is a negative number. |
| 348 |
|
| 349 |
0 is not negative. |
| 350 |
|
| 351 |
is_integer |
| 352 |
$is_an_integer = $thing->is_integer; |
| 353 |
|
| 354 |
Returns true if $thing is an integer. |
| 355 |
|
| 356 |
12->is_integer; # true |
| 357 |
12.34->is_integer; # false |
| 358 |
|
| 359 |
is_int |
| 360 |
A synonym for is_integer. |
| 361 |
|
| 362 |
is_decimal |
| 363 |
$is_a_decimal_number = $thing->is_decimal; |
| 364 |
|
| 365 |
Returns true if $thing is a decimal number. |
| 366 |
|
| 367 |
12->is_decimal; # false |
| 368 |
12.34->is_decimal; # true |
| 369 |
".34"->is_decimal; # true |
| 370 |
|
| 371 |
Reference Related Methods |
| 372 |
The following core functions are implemented. |
| 373 |
|
| 374 |
tie, tied, ref, vec. |
| 375 |
|
| 376 |
"tie", "tied", and "undef" don't work on code references. |
| 377 |
|
| 378 |
Array Methods |
| 379 |
Array methods work on both arrays and array references: |
| 380 |
|
| 381 |
my $arr = [ 1 .. 10 ]; |
| 382 |
$arr->undef; |
| 383 |
|
| 384 |
Or: |
| 385 |
|
| 386 |
my @arr = ( 1 .. 10 ); |
| 387 |
@arr->undef; |
| 388 |
|
| 389 |
List context forces methods to return a list: |
| 390 |
|
| 391 |
my @arr = ( 1 .. 10 ); |
| 392 |
print join ' -- ', @arr->grep(sub { $_ > 3 }), "\n"; |
| 393 |
|
| 394 |
Likewise, scalar context forces methods to return an array reference. |
| 395 |
|
| 396 |
As scalar context forces methods to return a reference, methods may be |
| 397 |
chained |
| 398 |
|
| 399 |
my @arr = ( 1 .. 10 ); |
| 400 |
@arr->grep(sub { $_ > 3 })->min->say; # "4\n"; |
| 401 |
|
| 402 |
These built-in functions are defined as methods: |
| 403 |
|
| 404 |
pop, push, shift, unshift, delete, undef, exists, bless, tie, tied, ref, |
| 405 |
grep, map, join, reverse, and sort, each. |
| 406 |
|
| 407 |
As well as: |
| 408 |
|
| 409 |
vdelete |
| 410 |
Deletes a specified value from the array. |
| 411 |
|
| 412 |
$a = 1->to(10); |
| 413 |
$a->vdelete(3); # deletes 3 |
| 414 |
$a->vdelete(2)->say; # "1 4 5 6 7 8 9 10\n" |
| 415 |
|
| 416 |
uniq |
| 417 |
Removes all duplicate elements from an array and returns the new array |
| 418 |
with no duplicates. |
| 419 |
|
| 420 |
my @array = qw( 1 1 2 3 3 6 6 ); |
| 421 |
@return = @array->uniq; # @return : 1 2 3 6 |
| 422 |
|
| 423 |
first |
| 424 |
Returns the first element of an array for which a callback returns true: |
| 425 |
|
| 426 |
$arr->first(sub { qr/5/ }); |
| 427 |
|
| 428 |
max |
| 429 |
Returns the largest numerical value in the array. |
| 430 |
|
| 431 |
$a = 1->to(10); |
| 432 |
$a->max; # 10 |
| 433 |
|
| 434 |
min |
| 435 |
Returns the smallest numerical value in the array. |
| 436 |
|
| 437 |
$a = 1->to(10); |
| 438 |
$a->min; # 1 |
| 439 |
|
| 440 |
mean |
| 441 |
Returns the mean of elements of an array. |
| 442 |
|
| 443 |
$a = 1->to(10); |
| 444 |
$a->mean; # 55/10 |
| 445 |
|
| 446 |
var |
| 447 |
Returns the variance of the elements of an array. |
| 448 |
|
| 449 |
$a = 1->to(10); |
| 450 |
$a->var; # 33/4 |
| 451 |
|
| 452 |
svar |
| 453 |
Returns the standard variance. |
| 454 |
|
| 455 |
$a = 1->to(10); |
| 456 |
$a->svar; # 55/6 |
| 457 |
|
| 458 |
at |
| 459 |
Returns the element at a specified index. This function does not modify |
| 460 |
the original array. |
| 461 |
|
| 462 |
$a = 1->to(10); |
| 463 |
$a->at(2); # 3 |
| 464 |
|
| 465 |
size, elems, length |
| 466 |
"size", "elems" and "length" all return the number of elements in an |
| 467 |
array. |
| 468 |
|
| 469 |
my @array = qw(foo bar baz); |
| 470 |
@array->size; # 3 |
| 471 |
|
| 472 |
elements, flatten |
| 473 |
my @copy_of_array = $array->flatten; |
| 474 |
|
| 475 |
Returns the elements of an array ref as an array. This is the same as |
| 476 |
"@{$array}". |
| 477 |
|
| 478 |
Arrays can be iterated on using "for" and "foreach". Both take a code |
| 479 |
reference as the body of the for statement. |
| 480 |
|
| 481 |
foreach |
| 482 |
@array->foreach(\&code); |
| 483 |
|
| 484 |
Calls &code on each element of the @array in order. &code gets the |
| 485 |
element as its argument. |
| 486 |
|
| 487 |
@array->foreach(sub { print $_[0] }); # print each element of the array |
| 488 |
|
| 489 |
for |
| 490 |
@array->for(\&code); |
| 491 |
|
| 492 |
Like foreach, but &code is called with the index, the value and the |
| 493 |
array itself. |
| 494 |
|
| 495 |
my $arr = [ 1 .. 10 ]; |
| 496 |
$arr->for(sub { |
| 497 |
my($idx, $value) = @_; |
| 498 |
print "Value #$idx is $value\n"; |
| 499 |
}); |
| 500 |
|
| 501 |
sum |
| 502 |
my $sum = @array->sum; |
| 503 |
|
| 504 |
Adds together all the elements of the array. |
| 505 |
|
| 506 |
count |
| 507 |
Returns the number of elements in array that are "eq" to a specified |
| 508 |
value: |
| 509 |
|
| 510 |
my @array = qw/one two two three three three/; |
| 511 |
my $num = @array->count('three'); # returns 3 |
| 512 |
|
| 513 |
to, upto, downto |
| 514 |
"to", "upto", and "downto" create array references: |
| 515 |
|
| 516 |
1->to(5); # creates [1, 2, 3, 4, 5] |
| 517 |
1->upto(5); # creates [1, 2, 3, 4, 5] |
| 518 |
5->downto(5); # creates [5, 4, 3, 2, 1] |
| 519 |
|
| 520 |
Those wrap the ".." operator. |
| 521 |
|
| 522 |
Note while working with negative numbers you need to use () so as to |
| 523 |
avoid the wrong evaluation. |
| 524 |
|
| 525 |
my $range = 10->to(1); # this works |
| 526 |
my $range = -10->to(10); # wrong, interpreted as -( 10->to(10) ) |
| 527 |
my $range = (-10)->to(10); # this works |
| 528 |
|
| 529 |
head |
| 530 |
Returns the first element from @list. This differs from shift in that it |
| 531 |
does not change the array. |
| 532 |
|
| 533 |
my $first = @list->head; |
| 534 |
|
| 535 |
tail |
| 536 |
Returns all but the first element from @list. |
| 537 |
|
| 538 |
my @list = qw(foo bar baz quux); |
| 539 |
my @rest = @list->tail; # [ 'bar', 'baz', 'quux' ] |
| 540 |
|
| 541 |
Optionally, you can pass a number as argument to ask for the last $n |
| 542 |
elements: |
| 543 |
|
| 544 |
@rest = @list->tail(2); # [ 'baz', 'quux' ] |
| 545 |
|
| 546 |
slice |
| 547 |
Returns a list containing the elements from @list at the indices |
| 548 |
@indices. In scalar context, returns an array reference. |
| 549 |
|
| 550 |
# Return $list[1], $list[2], $list[4] and $list[8]. |
| 551 |
my @sublist = @list->slice(1,2,4,8); |
| 552 |
|
| 553 |
range |
| 554 |
"range" returns a list containing the elements from @list with indices |
| 555 |
ranging from $lower_idx to $upper_idx. It returns an array reference in |
| 556 |
scalar context. |
| 557 |
|
| 558 |
my @sublist = @list->range( $lower_idx, $upper_idx ); |
| 559 |
|
| 560 |
last_index |
| 561 |
my $index = @array->last_index(qr/.../); |
| 562 |
|
| 563 |
Returns the highest index whose element matches the given regular |
| 564 |
expression. |
| 565 |
|
| 566 |
my $index = @array->last_index(\&filter); |
| 567 |
|
| 568 |
Returns the highest index for an element on which the filter returns |
| 569 |
true. The &filter is passed in each value of the @array. |
| 570 |
|
| 571 |
my @things = qw(pear poll potato tomato); |
| 572 |
my $last_p = @things->last_index(qr/^p/); # 2 |
| 573 |
|
| 574 |
Called with no arguments, it corresponds to $#array giving the highest |
| 575 |
index of the array. |
| 576 |
|
| 577 |
my $index = @array->last_index; |
| 578 |
|
| 579 |
first_index |
| 580 |
Works just like last_index but it will return the index of the *first* |
| 581 |
matching element. |
| 582 |
|
| 583 |
my $first_index = @array->first_index; # 0 |
| 584 |
|
| 585 |
my @things = qw(pear poll potato tomato); |
| 586 |
my $last_p = @things->first_index(qr/^t/); # 3 |
| 587 |
|
| 588 |
at |
| 589 |
my $value = $array->at($index); |
| 590 |
|
| 591 |
Equivalent to "$array->[$index]". |
| 592 |
|
| 593 |
Hash Methods |
| 594 |
Hash methods work on both hashes and hash references. |
| 595 |
|
| 596 |
The built in functions work as normal: |
| 597 |
|
| 598 |
delete, exists, keys, values, bless, tie, tied, ref, undef, |
| 599 |
|
| 600 |
at, get |
| 601 |
my @values = %hash->get(@keys); |
| 602 |
|
| 603 |
Returns the @values of @keys. |
| 604 |
|
| 605 |
put |
| 606 |
%hash->put(%other_hash); |
| 607 |
|
| 608 |
Overlays %other_hash on top of %hash. |
| 609 |
|
| 610 |
my $h = {a => 1, b => 2}; |
| 611 |
$h->put(b => 99, c => 3); # (a => 1, b => 99, c => 3) |
| 612 |
|
| 613 |
set |
| 614 |
Synonym for put. |
| 615 |
|
| 616 |
each |
| 617 |
Like "foreach" but for hash references. For each key in the hash, the |
| 618 |
code reference is invoked with the key and the corresponding value as |
| 619 |
arguments: |
| 620 |
|
| 621 |
my $hashref = { foo => 10, bar => 20, baz => 30, quux => 40 }; |
| 622 |
$hashref->each(sub { print $_[0], ' is ', $_[1], "\n" }); |
| 623 |
|
| 624 |
Or: |
| 625 |
|
| 626 |
my %hash = ( foo => 10, bar => 20, baz => 30, quux => 40 ); |
| 627 |
%hash->each(sub { print $_[0], ' is ', $_[1], "\n" }); |
| 628 |
|
| 629 |
Unlike regular "each", this each will always iterate through the entire |
| 630 |
hash. |
| 631 |
|
| 632 |
Hash keys appear in random order that varies from run to run (this is |
| 633 |
intentional, to avoid calculated attacks designed to trigger algorithmic |
| 634 |
worst case scenario in "perl"'s hash tables). |
| 635 |
|
| 636 |
You can get a sorted "foreach" by combining "keys", "sort", and |
| 637 |
"foreach": |
| 638 |
|
| 639 |
%hash->keys->sort->foreach(sub { |
| 640 |
print $_[0], ' is ', $hash{$_[0]}, "\n"; |
| 641 |
}); |
| 642 |
|
| 643 |
lock_keys |
| 644 |
%hash->lock_keys; |
| 645 |
|
| 646 |
Works as "lock_keys" in Hash::Util. No more keys may be added to the |
| 647 |
hash. |
| 648 |
|
| 649 |
slice |
| 650 |
Takes a list of hash keys and returns the corresponding values e.g. |
| 651 |
|
| 652 |
my %hash = ( |
| 653 |
one => 'two', |
| 654 |
three => 'four', |
| 655 |
five => 'six' |
| 656 |
); |
| 657 |
|
| 658 |
print %hash->slice(qw(one five))->join(' and '); # prints "two and six" |
| 659 |
|
| 660 |
flip |
| 661 |
Exchanges values for keys in a hash: |
| 662 |
|
| 663 |
my %things = ( foo => 1, bar => 2, baz => 5 ); |
| 664 |
my %flipped = %things->flip; # { 1 => foo, 2 => bar, 5 => baz } |
| 665 |
|
| 666 |
If there is more than one occurrence of a certain value, any one of the |
| 667 |
keys may end up as the value. This is because of the random ordering of |
| 668 |
hash keys. |
| 669 |
|
| 670 |
# Could be { 1 => foo }, { 1 => bar }, or { 1 => baz } |
| 671 |
{ foo => 1, bar => 1, baz => 1 }->flip; |
| 672 |
|
| 673 |
Because references cannot usefully be keys, it will not work where the |
| 674 |
values are references. |
| 675 |
|
| 676 |
{ foo => [ 'bar', 'baz' ] }->flip; # dies |
| 677 |
|
| 678 |
flatten |
| 679 |
my %hash = $hash_ref->flatten; |
| 680 |
|
| 681 |
Dereferences a hash reference. |
| 682 |
|
| 683 |
Code Methods |
| 684 |
Methods which work on code references. |
| 685 |
|
| 686 |
These are simple wrappers around the Perl core functions. bless, ref, |
| 687 |
|
| 688 |
Due to Perl's precedence rules, some autoboxed literals may need to be |
| 689 |
parenthesized. For instance, this works: |
| 690 |
|
| 691 |
my $curried = sub { ... }->curry(); |
| 692 |
|
| 693 |
This does not: |
| 694 |
|
| 695 |
my $curried = \&foo->curry(); |
| 696 |
|
| 697 |
The solution is to wrap the reference in parentheses: |
| 698 |
|
| 699 |
my $curried = (\&foo)->curry(); |
| 700 |
|
| 701 |
curry |
| 702 |
my $curried_code = $code->curry(5); |
| 703 |
|
| 704 |
Currying takes a code reference and provides the same code, but with the |
| 705 |
first argument filled in. |
| 706 |
|
| 707 |
my $greet_world = sub { |
| 708 |
my($greeting, $place) = @_; |
| 709 |
return "$greeting, $place!"; |
| 710 |
}; |
| 711 |
print $greet_world->("Hello", "world"); # "Hello, world!" |
| 712 |
|
| 713 |
my $howdy_world = $greet_world->curry("Howdy"); |
| 714 |
print $howdy_world->("Texas"); # "Howdy, Texas!" |
| 715 |
|
| 716 |
What's Missing? |
| 717 |
* File and socket operations are already implemented in an |
| 718 |
object-oriented fashion care of IO::Handle, IO::Socket::INET, and |
| 719 |
IO::Any. |
| 720 |
|
| 721 |
* Functions listed in the perlfunc headings |
| 722 |
|
| 723 |
* "System V interprocess communication functions", |
| 724 |
|
| 725 |
* "Fetching user and group info", |
| 726 |
|
| 727 |
* "Fetching network info", |
| 728 |
|
| 729 |
* "Keywords related to perl modules", |
| 730 |
|
| 731 |
* "Functions for processes and process groups", |
| 732 |
|
| 733 |
* "Keywords related to scoping", |
| 734 |
|
| 735 |
* "Time-related functions", |
| 736 |
|
| 737 |
* "Keywords related to the control flow of your perl program", |
| 738 |
|
| 739 |
* "Functions for filehandles, files, or directories", |
| 740 |
|
| 741 |
* "Input and output functions". |
| 742 |
|
| 743 |
* (Most) binary operators |
| 744 |
|
| 745 |
These things are likely implemented in an object oriented fashion by |
| 746 |
other CPAN modules, are keywords and not functions, take no arguments, |
| 747 |
or don't make sense as part of the string, number, array, hash, or code |
| 748 |
API. |
| 749 |
|
| 750 |
Autoboxing |
| 751 |
*This section quotes four pages from the manuscript of Perl 6 Now: The |
| 752 |
Core Ideas Illustrated with Perl 5 by Scott Walters. The text appears in |
| 753 |
the book starting at page 248. This copy lacks the benefit of copyedit - |
| 754 |
the finished product is of higher quality.* |
| 755 |
|
| 756 |
A *box* is an object that contains a primitive variable. Boxes are used |
| 757 |
to endow primitive types with the capabilities of objects which |
| 758 |
essential in strongly typed languages but never strictly required in |
| 759 |
Perl. Programmers might write something like "my $number = Int->new(5)". |
| 760 |
This is manual boxing. To *autobox* is to convert a simple type into an |
| 761 |
object type automatically, or only conceptually. This is done by the |
| 762 |
language. |
| 763 |
|
| 764 |
*autobox*ing makes a language look to programmers as if everything is an |
| 765 |
object while the interpreter is free to implement data storage however |
| 766 |
it pleases. Autoboxing is really making simple types such as numbers, |
| 767 |
strings, and arrays appear to be objects. |
| 768 |
|
| 769 |
"int", "num", "bit", "str", and other types with lower case names, are |
| 770 |
primitives. They're fast to operate on, and require no more memory to |
| 771 |
store than the data held strictly requires. "Int", "Num", "Bit", "Str", |
| 772 |
and other types with an initial capital letter, are objects. These may |
| 773 |
be subclassed (inherited from) and accept traits, among other things. |
| 774 |
These objects are provided by the system for the sole purpose of |
| 775 |
representing primitive types as objects, though this has many ancillary |
| 776 |
benefits such as making "is" and "has" work. Perl provides "Int" to |
| 777 |
encapsulate an "int", "Num" to encapsulate a "num", "Bit" to encapsulate |
| 778 |
a "bit", and so on. As Perl's implementations of hashes and dynamically |
| 779 |
expandable arrays store any type, not just objects, Perl programmers |
| 780 |
almost never are required to box primitive types in objects. Perl's |
| 781 |
power makes this feature less essential than it is in other languages. |
| 782 |
|
| 783 |
*autobox*ing makes primitive objects and they're boxed versions |
| 784 |
equivalent. An "int" may be used as an "Int" with no constructor call, |
| 785 |
no passing, nothing. This applies to constants too, not just variables. |
| 786 |
This is a more Perl 6 way of doing things. |
| 787 |
|
| 788 |
# Perl 6 - autoboxing associates classes with primitives types: |
| 789 |
|
| 790 |
print 4.sqrt, "\n"; |
| 791 |
|
| 792 |
print [ 1 .. 20 ].elems, "\n"; |
| 793 |
|
| 794 |
The language is free to implement data storage however it wishes but the |
| 795 |
programmer sees the variables as objects. |
| 796 |
|
| 797 |
Expressions using autoboxing read somewhat like Latin suffixes. In the |
| 798 |
autoboxing mind-set, you might not say that something is "made more |
| 799 |
mnemonic", but has been "mnemonicified". |
| 800 |
|
| 801 |
Autoboxing may be mixed with normal function calls. In the case where |
| 802 |
the methods are available as functions and the functions are available |
| 803 |
as methods, it is only a matter of personal taste how the expression |
| 804 |
should be written: |
| 805 |
|
| 806 |
# Calling methods on numbers and strings, these three lines are equivalent |
| 807 |
# Perl 6 |
| 808 |
|
| 809 |
print sqrt 4; |
| 810 |
print 4.sqrt; |
| 811 |
4.sqrt.print; |
| 812 |
|
| 813 |
The first of these three equivalents assumes that a global "sqrt()" |
| 814 |
function exists. This first example would fail to operate if this global |
| 815 |
function were removed and only a method in the "Num" package was left. |
| 816 |
|
| 817 |
Perl 5 had the beginnings of autoboxing with filehandles: |
| 818 |
|
| 819 |
use IO::Handle; |
| 820 |
open my $file, '<', 'file.txt' or die $!; |
| 821 |
$file->read(my $data, -s $file); |
| 822 |
|
| 823 |
Here, "read" is a method on a filehandle we opened but *never blessed*. |
| 824 |
This lets us say things like "$file->print(...)" rather than the often |
| 825 |
ambagious "print $file ...". |
| 826 |
|
| 827 |
To many people, much of the time, it makes more conceptual sense as |
| 828 |
well. |
| 829 |
|
| 830 |
Reasons to Box Primitive Types |
| 831 |
What good is all of this? |
| 832 |
|
| 833 |
* Makes conceptual sense to programmers used to object interfaces as |
| 834 |
*the* way to perform options. |
| 835 |
|
| 836 |
* Alternative idiom. Doesn't require the programmer to write or read |
| 837 |
expressions with complex precedence rules or strange operators. |
| 838 |
|
| 839 |
* Many times that parenthesis would otherwise have to span a large |
| 840 |
expression, the expression may be rewritten such that the |
| 841 |
parenthesis span only a few primitive types. |
| 842 |
|
| 843 |
* Code may often be written with fewer temporary variables. |
| 844 |
|
| 845 |
* Autoboxing provides the benefits of boxed types without the memory |
| 846 |
bloat of actually using objects to represent primitives. Autoboxing |
| 847 |
"fakes it". |
| 848 |
|
| 849 |
* Strings, numbers, arrays, hashes, and so on, each have their own |
| 850 |
API. Documentation for an "exists" method for arrays doesn't have to |
| 851 |
explain how hashes are handled and vice versa. |
| 852 |
|
| 853 |
* Perl tries to accommodate the notion that the "subject" of a |
| 854 |
statement should be the first thing on the line, and autoboxing |
| 855 |
furthers this agenda. |
| 856 |
|
| 857 |
Perl is an idiomatic language and this is an important idiom. |
| 858 |
|
| 859 |
Subject First: An Aside |
| 860 |
Perl's design philosophy promotes the idea that the language should be |
| 861 |
flexible enough to allow programmers to place the subject of a statement |
| 862 |
first. For example, "die $! unless read $file, 60" looks like the |
| 863 |
primary purpose of the statement is to "die". |
| 864 |
|
| 865 |
While that might be the programmers primary goal, when it isn't, the |
| 866 |
programmer can communicate his real primary intention to programmers by |
| 867 |
reversing the order of clauses while keeping the exact same logic: "read |
| 868 |
$file, 60 or die $!". |
| 869 |
|
| 870 |
Autoboxing is another way of putting the subject first. |
| 871 |
|
| 872 |
Nouns make good subjects, and in programming, variables, constants, and |
| 873 |
object names are the nouns. Function and method names are verbs. |
| 874 |
"$noun->verb()" focuses the readers attention on the thing being acted |
| 875 |
on rather than the action being performed. Compare to "$verb($noun)". |
| 876 |
|
| 877 |
Autoboxing and Method Results |
| 878 |
Let's look at some examples of ways an expression could be written. |
| 879 |
|
| 880 |
# Various ways to do the same thing: |
| 881 |
|
| 882 |
print(reverse(sort(keys(%hash)))); # Perl 5 - pathological parenthetic |
| 883 |
print reverse sort keys %hash; # Perl 5 - no unneeded parenthesis |
| 884 |
|
| 885 |
print(reverse(sort(%hash,keys)))); # Perl 6 - pathological |
| 886 |
print reverse sort %hash.keys; # Perl 6 - no unneeded parenthesis |
| 887 |
|
| 888 |
%hash.keys ==> sort ==> reverse ==> print; # Perl 6 - pipeline operator |
| 889 |
|
| 890 |
%hash.keys.sort.reverse.print; # Perl 6 - autobox |
| 891 |
|
| 892 |
%hash->keys->sort->reverse->print; # Perl 5 - autobox |
| 893 |
|
| 894 |
This section deals with the last two of these equivalents. These are |
| 895 |
method calls |
| 896 |
|
| 897 |
use autobox::Core; |
| 898 |
use Perl6::Contexts; |
| 899 |
|
| 900 |
my %hash = (foo => 'bar', baz => 'quux'); |
| 901 |
|
| 902 |
%hash->keys->sort->reverse->print; # Perl 5 - autobox |
| 903 |
|
| 904 |
# prints "foo baz" |
| 905 |
|
| 906 |
Each method call returns an array reference, in this example. Another |
| 907 |
method call is immediately performed on this value. This feeding of the |
| 908 |
next method call with the result of the previous call is the common mode |
| 909 |
of use of autoboxing. Providing no other arguments to the method calls, |
| 910 |
however, is not common. |
| 911 |
|
| 912 |
"Perl6::Contexts" recognizes object context as provided by "->" and |
| 913 |
coerces %hash and @array into references, suitable for use with |
| 914 |
"autobox". (Note that "autobox" also does this automatically as of |
| 915 |
version 2.40.) |
| 916 |
|
| 917 |
"autobox" associates primitive types, such as references of various |
| 918 |
sorts, with classes. "autobox::Core" throws into those classes methods |
| 919 |
wrapping Perl's built-in functions. In the interest of full disclosure, |
| 920 |
"Perl6::Contexts" and "autobox::Core" are my creations. |
| 921 |
|
| 922 |
Autobox to Simplify Expressions |
| 923 |
One of my pet peeves in programming is parenthesis that span large |
| 924 |
expression. It seems like about the time I'm getting ready to close the |
| 925 |
parenthesis I opened on the other side of the line, I realize that I've |
| 926 |
forgotten something, and I have to arrow back over or grab the mouse. |
| 927 |
|
| 928 |
When the expression is too long to fit on a single line, it gets broken |
| 929 |
up, then I must decide how to indent it if it grows to 3 or more lines. |
| 930 |
|
| 931 |
# Perl 5 - a somewhat complex expression |
| 932 |
|
| 933 |
print join("\n", map { CGI::param($_) } @cgi_vars), "\n"; |
| 934 |
# Perl 5 - again, using autobox: |
| 935 |
|
| 936 |
@cgi_vars->map(sub { CGI::param($_[0]) })->join("\n")->concat("\n")->print; |
| 937 |
|
| 938 |
The autoboxed version isn't shorter, but it reads from left to right, |
| 939 |
and the parenthesis from the "join()" don't span nearly as many |
| 940 |
characters. The complex expression serving as the value being "join()"ed |
| 941 |
in the non-autoboxed version becomes, in the autoboxed version, a value |
| 942 |
to call the "join()" method on. |
| 943 |
|
| 944 |
This "print" statement takes a list of CGI parameter names, reads the |
| 945 |
values for each parameter, joins them together with newlines, and prints |
| 946 |
them with a newline after the last one. |
| 947 |
|
| 948 |
Pretending that this expression were much larger and it had to be broken |
| 949 |
to span several lines, or pretending that comments are to be placed |
| 950 |
after each part of the expression, you might reformat it as such: |
| 951 |
|
| 952 |
@cgi_vars->map(sub { CGI::param($_[0]) }) # turn CGI arg names into values |
| 953 |
->join("\n") # join with newlines |
| 954 |
->concat("\n") # give it a trailing newline |
| 955 |
->print; # print them all out |
| 956 |
|
| 957 |
*Here ends the text quoted from the Perl 6 Now manuscript.* |
| 958 |
|
| 959 |
BUGS |
| 960 |
Yes. Report them to the author, [email protected], or post them to |
| 961 |
GitHub's bug tracker at |
| 962 |
<https://github.com/scrottie/autobox-Core/issues>. |
| 963 |
|
| 964 |
The API is not yet stable -- Perl 6-ish things and local extensions are |
| 965 |
still being renamed. |
| 966 |
|
| 967 |
HISTORY |
| 968 |
See the Changes file. |
| 969 |
|
| 970 |
COPYRIGHT AND LICENSE |
| 971 |
Copyright (C) 2009, 2010, 2011 by Scott Walters and various contributors |
| 972 |
listed (and unlisted) below. |
| 973 |
|
| 974 |
This library is free software; you can redistribute it and/or modify it |
| 975 |
under the same terms as Perl itself, either Perl version 5.8.9 or, at |
| 976 |
your option, any later version of Perl 5 you may have available. |
| 977 |
|
| 978 |
This library is distributed in the hope that it will be useful, but |
| 979 |
without any warranty; without even the implied warranty of |
| 980 |
merchantability or fitness for a particular purpose. |
| 981 |
|
| 982 |
SEE ALSO |
| 983 |
autobox |
| 984 |
Moose::Autobox |
| 985 |
Perl6::Contexts |
| 986 |
<http://github.com/gitpan/autobox-Core> |
| 987 |
IO::Any |
| 988 |
Perl 6: <http://dev.perl.org/perl6/apocalypse/>. |
| 989 |
|
| 990 |
AUTHORS |
| 991 |
Scott Walters, [email protected]. |
| 992 |
|
| 993 |
Tomasz Konojacki has been assisting with maint. |
| 994 |
|
| 995 |
Jacinta Richardson improved documentation and tidied up the interface. |
| 996 |
|
| 997 |
Michael Schwern and the perl5i contributors for tests, code, and |
| 998 |
feedback. |
| 999 |
|
| 1000 |
JJ contributed a "strip" method for scalars - thanks JJ! |
| 1001 |
|
| 1002 |
Ricardo SIGNES contributed patches. |
| 1003 |
|
| 1004 |
Thanks to Matt Spear, who contributed tests and definitions for numeric |
| 1005 |
operations. |
| 1006 |
|
| 1007 |
Mitchell N Charity reported a bug and sent a fix. |
| 1008 |
|
| 1009 |
Thanks to chocolateboy for autobox and for the encouragement. |
| 1010 |
|
| 1011 |
Thanks to Bruno Vecchi for bug fixes and many, many new tests going into |
| 1012 |
version 0.8. |
| 1013 |
|
| 1014 |
Thanks to <http://github.com/daxim> daxim/Lars DIECKOW pushing in fixes |
| 1015 |
and patches from the RT queue along with fixes to build and additional |
| 1016 |
doc examples. |
| 1017 |
|
| 1018 |
Thanks to everyone else who sent fixes or suggestions -- apologies if I |
| 1019 |
failed to include you here! |
| 1020 |
|