Cn-Util

 view release on metacpan or  search on metacpan

README.md  view on Meta::CPAN

# Functions

All functions are exported by default.

## dir

    my @files = dir(dir => '/data', regex => '\.csv$');
    my @tree  = dir(dir => '/data', regex => '\.csv$', recursive => 1, cpu => 8);
    dir(dir => '/data', recursive => 1, on_match => sub { say $_[0] });

Returns the paths under `dir` whose base name matches `regex` and that pass every file test in `tests`.  The paths are `dir` joined to the entry with `/`; with the default `dir => '.'`, the leading `./` is left off.  `.` and `..` are never returned.

It takes these named arguments:

* `dir` (default `.`): The directory to list.  Trailing slashes are removed, but `/` stays `/`.  A `dir` that is a symbolic link to a directory is listed through the link, recursively or not.
* `regex` (default `.`): A pattern the base name must match, given as a string or a `qr//`.  An invalid pattern dies, naming it.
* `tests` (default `f`): One or more of perl's file tests, as letters: `rwxoRWXOezsfdlpSbcugkTB`.  Every one must pass.  `'d'` lists directories; `''` applies no test at all.
* `recursive` (default `0`): `1` descends into subdirectories, without following symbolic links.
* `cpu` (default `1`): For a recursive listing, the number of worker processes (through `Parallel::ForkManager`).  Ignored when `recursive` is `0`.
* `on_match` (no default): A code reference called with each path as it is found; `dir` then returns an empty list, so a very large tree is never held in memory.

The file tests share one `stat` per path, so asking for four of them costs no more than asking for one.  `-l` is checked first, with `lstat`.

With `cpu` greater than 1, `dir` walks the tree breadth-first until one level holds four directories per worker, then shares those directories out.  The results are the same as a serial walk, in a different order.  `on_match` still runs in the callin...

An unknown argument, an undefined `tests`, `dir`, `regex` or `cpu`, a letter that is not a file test, a `cpu` that is not a positive integer, an `on_match` that is not a code reference, and a directory that cannot be opened, whether `dir` itself or o...

## execute

    my $exit   = execute('make test');                  # 0, or dies
    my $out    = execute('git log -1 --format=%H', 'stdout');
    my $err    = execute('perl -c script.pl', 'stderr');
    my $all    = execute('ls /nonexistent', 'all', 0);  # does not die
    # $all = { exit => 512, stdout => '', stderr => "ls: cannot access ..." }

Runs `$cmd` through the shell with `system`, capturing its standard output and standard error with `Capture::Tiny`.  The second argument says what to return:

* `exit` (the default): the wait status, `$?` -- 0 for success, 256 for `exit 1`
* `stdout`: standard output, chomped
* `stderr`: standard error, chomped
* `all`: a hash reference with `exit`, `stdout` and `stderr`

The third argument, `$die`, is true by default: a command that exits non-zero prints its exit status, standard output and standard error to `STDERR` and dies.  Pass a false value, such as 0, to have the status returned instead.

The command's standard input is an empty pipe.  A command that would prompt -- `rm` on a write-protected file, `cp -i` -- reads end-of-file and declines rather than waiting, unseen, for an answer.  The caller's `STDIN` is not touched, so input it has...

## file2string

    my $text = file2string('notes.txt');

Returns the whole of a file as one string, read without any decoding layer.  A file that cannot be opened or read, such as a directory, dies, naming it.

## format_commas

    format_commas(1234567.891);         # '1,234,567.89'
    format_commas(1234567, '%.0u');     # '1,234,567'
    format_commas(999999.999);          # '1,000,000.00'
    format_commas(-0.5);                # '-0.50'
    format_commas(1e20);                # '100,000,000,000,000,000,000.00'

Puts a comma between each group of three digits of the integer part and appends the hundredths, rounded half up.  The second argument is the `sprintf` format the hundredths are printed with, `'.%02d'` by default; `'%.0u'` rounds half up to a whole nu...

What is rounded is the number perl holds, which is binary, not the decimal written in the source.  Most decimal fractions have no exact binary form, so a value written as exactly half a cent is stored a little above or below it, and rounds accordingl...

## json_file_to_ref

    my $ref = json_file_to_ref('results.json');

Reads a JSON file and returns the decoded data, through `JSON::MaybeXS`.  Python's `json` module and NumPy write `NaN`, `Infinity` and `-Infinity` as bare words, which are not JSON; where one of those stands as a value, or is the whole document, it i...

## ref_to_json_file

    ref_to_json_file($data, 'results.json');   # prints "Wrote results.json"

Writes a data structure to a file as JSON, through `JSON::MaybeXS`, prints `Wrote` and the file name, and returns the file name.  The name is colored by the rule `structure`'s `color => 'auto'` follows: when `STDOUT` is a terminal, or `CLICOLOR_FORCE...

## random_key, random_value

    my $key   = random_key(\%hash);
    my $value = random_value(\%hash);

Return one key, or one value, of a hash -- whichever pair perl's hash iterator yields first, which is quick no matter how big the hash is.  This is *any* key, not a randomly chosen one: the same hash returns the same pair each time.  It is useful for...

Both reset the hash's iterator, so do not call them on a hash in the middle of an `each` loop.

## structure

    my $text = structure($ref, output => 'string');
    structure(\%config, max_depth => 2, as => 'config');

Prints the *shape* of a data structure rather than its values: `p` shows every element of a 50,000-element array of records, while `structure` merges them into one and shows the record once.

    my @people = (
        { name => 'Ann', age => 31, langs => ['perl', 'R'] },
        { name => 'Bo',  age => 28, langs => [], email => undef },
    );
    st @people;

prints

    ARRAY[2]
        [*]: HASH{4} (from 2 instances)
            age: number
            email?: null
            langs: ARRAY[0-2] (from 2 instances)
                [*]: string
            name: string

A key that only some of the merged hashes have is marked `?`.  Values in the same place that are of different kinds are shown as a `UNION` of each kind.  Arrays show the range of their lengths.  Blessed references show their class.  A reference to so...

It takes these options after the reference:

* `output` (default `stdout`): `stdout` or `stderr` to print there; `string` to print nothing.  The text is returned in every case.
* `color` (default `auto`): `1` or `0`.  `auto` colours the output when it goes to a terminal, or when `CLICOLOR_FORCE` is set, unless `NO_COLOR` is set.
* `max_depth` (default `0`): How many levels to descend before printing `(...)`; `0` is no limit.
* `hash_max` (default `32`): A hash with more keys than this is taken to be a lookup table, and its values are merged into one entry, `<*>`, rather than listed by key.  `0` lists every key.
* `as` (no default): A line to print above the structure.

## st

    st %hash;
    st @array;
    st $ref, max_depth => 2;

`structure`, called the way `p` is called: the argument is a variable, not a reference to one, and the options follow it.  As with `p`, it must be a variable -- `st(\%h)` and `st(func())` do not compile; call `structure` for those.

# Installation

    cpanm Cn::Util



( run in 0.655 second using v1.01-cache-2.11-cpan-60884a8df76 )