NAME

Hub::Perl::Language -

Top


SYNOPSIS

Top


DESCRIPTION

Top


PUBLIC METHODS

sizeof

Integer size of hashes, arrays, and scalars
 Usage: sizeof \%hash
 Usage: sizeof \@array
 Usage: sizeof \$scalar_ref
 Usage: sizeof $scalar
 Usage: sizeof \%more, \@than, $one

Sizes are computed as follows:

  HASH    - Number of keys in the hash
  ARRAY   - Number of elements
  SCALAR  - Length as returned by C<length()>

The total size of all arguments is returned.

Example: Hash: (matches)

    sizeof( { a=>1, b=>2, c=>3 } );
    3

Example: Array: (matches)

    sizeof( [ 'a1', 'b2', 'c3' ] );
    3

Example: Scalar: (matches)

    sizeof( "abc"                );
    3

Example: Scalar (ref): (matches)

    sizeof( \"abc"               );
    3

Example: Nothing: (matches)

    sizeof( undef                );
    0

Example: Multiple values: (matches)

    sizeof( "a", "b", "c"        );
    3

check

True if all items in list pass the test.
 Usage: check [OPTIONS], [TEST], LIST

OPTIONS:

  -opr    (or|and|xor)                            Operator  (default: 'and')

TEST:

  -test   (def|num|str|match|blessed|eval)        Test type (default: 'def')
  -isa    EXPR
  -ref    EXPR

OPERATORS:

  and             True when all items pass the test.
  or              True when any single item passes the test.
  xor             Alternation pattern. True unless two consecutive values
                  both pass or fail the test.

BASIC TEST:

  def             Items are defined
  num             Items are numeric
  str             Items are *not* numeric

OTHER TESTS:

  match=EXPR      Items match EXPR
  eval            Items are eval'd and truth is based on $@.  Note that the
                  eval *actually* happens, so don't do anything that will
                  break your code.  The intention of this check is for:

Example returns: abort:

    my $compression = check( '-test=eval', 'use IO::Zlib' ) ? 1 : 0;

STRUCTURE TESTS:

  blessed         Items are blessed
  ref=EXPR        Item's ref matches EXPR (does *not* include @ISA)
  isa=EXPR        Item's ref or @ISA match EXPR.  Much like UNIVERSAL::isa
                  except allows regular expressions.

Example: none are defined returns: false:

    check( undef, undef, undef );

Example: only one is defined returns: false:

    check( 1, undef );

Example: both are defined returns: true:

    check( 1, 1 );

Example: one is defined returns: true:

    check( 1, undef, -opr => 'or' );

Example returns: false:

    check( -opr => 'xor', 1, 1 );

Example returns: false:

    check( -opr => 'xor', undef, undef );

Example returns: true:

    check( -opr => 'xor', undef, 1 );

Example returns: true:

    check( -opr => 'xor', 1, undef );

Example returns: true:

    check( -opr => 'xor', 1, undef, 1, undef );

Example returns: false:

    check( -opr => 'xor', 1, undef, 1, 1, undef );

Example returns: true:

    check( -opr => 'xor', undef, 1, undef, 1 );

opts

 Usage: opts [OPTIONS], \ARRAY, [\HASH]

Split parameter arrays into options and arguments.

OPTIONS:

  -prefix=EXPR            # specify option prefix, default is single dash (-).
  -assign=EXPR            # specify assignment character, default is the
                            equal sign (=).
  -append=EXPR            # specify append character, default is the
                            plus sign (+).

In array context, we return two references. Which may cause confusion:

   my %opts = Hub::opts( \@_ );                # Wrong!
   my $opts = Hub::opts( \@_ );                # Correct!
   my ($opts,$args) = Hub::opts( \@_ );        # Correct!

Options are extracted (via splice) from the referenced array. The advantage is both for performance (don't make a copy of the array), and so you may use @_ (or @ARGV, etc) normally, as data:

Example: at-underscore contains everyting but the '-with' option: (matches)

   sub myjoin {
      my $opts = Hub::opts( @_ );
      return join( $$opts{'with'}, @_ );
   }
   myjoin( 'a', 'b', '-with=;', 'c', 'd' );
    a;b;c;d

1. Arguments are elements which do *not* begin with a dash (-).

2. Options are elements which begin with a single dash (-) and are not negative numbers.

3. An option of '-opts' is reserved for passing in already parsed option hashes.

4. Options will have their leading dash (-) removed.

5. Options values are formed as:

  Given:                  opt1 will be:       because:
  -opt1=value             'value'             contains an equal sign
  -opt1 nextelem          'nextelem'          next element is *not* an option
  -opt1 -option2          1                   next element is also an option
  -opt1                   1                   it is the last element
  -opt1                   1                   it is the last element
  -opt1=a -opt1=b         b                   last one wins
  -opt1=a +opt1=b         [ 'a', 'b' ]        it was specified using '+'
  +opt1=a +opt1=b         [ 'a', 'b' ]        they can both be '+'

For example:

  my($opts,$args) = Hub::opts( [ 'a', 'b', '-c' => 'c', '-x', '-o=out' ] );
  print "Opts:\n", Hub::hprint( $opts );
  print "Args:\n", Hub::hprint( $args );

Will print:

  Opts:
  c => c
  o => out
  x => 1
  Args:
  a
  b

objopts

Split @_ into ($self,$opts), leaving @_ with remaining items.
 Usage: objopts \@params, [\%defaults]

Convienence method for splitting instance method parameters.

Returns an array.

Example: Test return value: (matches)

  my $obj = mkinst( 'Object' );
  my @result = objopts( [ $obj ] );
  join( ',', map { ref($_) } @result );
    Hub::Base::Object,

cmdopts

Extract short and long options from @ARGV
 Usage: cmdopts \@arguments
 Usage: cmdopts \@arguments, \%default_options

Single-dash paramaters are always boolean flags. Flags are broken apart such that:

  -lal

becomes

  -l -a -l

To create a list (ARRAY) of items, use '++' where you would normally use '--'.

Example: (matches)

  my $opts = cmdopts(['--letters=a', '++letters=b', '++letters=c']);
  join('-', @{$$opts{'letters'}});
    a-b-c

subst

 Usage: subst

Call to perl's substitution operator. Represented here as a function to facilitate transformation by reducing the need for temporaries. In essence, the goal is to reduce:

  my $bakname = getfilename();
  $bakname =~ s/\.db$/\.bak/;

to:

  my $bakname = Hub::subst( getfilename(), '\.db$', '.bak' );

without modifying the original string returned by getfilename().

getuid

Return the UID of the provided user
 Usage: getuid $user_name
If perl has not been compiled with 'getpwnam', $user_name is returned.

-1 is returned when no user is found

getgid

Return the GID of the provided group
 Usage: getgid - $group_name
If perl has not been compiled with 'getgrnam', $group_name is returned.

-1 is returned when no group is found

touch

 Usage: touch LIST

Changes the access and modification times on each file of a list of files.

expect

Croak if arguments do not match their expected type
 Usage: expect [OPTIONS], [TEST], LIST

OPTIONS:

  -back   \d      # Carp level (for reporting further up the callstack)
  -not    0|1     # Invert the result

TESTS:

  -blessed        # All LIST items are blessed
  -match=EXPR     # All LIST items match /EXPR/
  -ref=EXPR       # All LIST items' ref match /EXPR/

By default, LIST is made up of key/value pairs, where the key is the type (what ref() will return) and the value is what will be tested. LIST may contain one or more key/value pairs such as:

  HASH            => arg
  REF             => arg
  My::Package     => arg

Example returns: true:

    Hub::expect( -match => 'and|or|xor', 'and' );

Example returns: true:

    Hub::expect( HASH => {}, HASH => {} );

Example returns: abort:

    Hub::expect( -blessed => {} );

Example returns: true:

    Hub::expect( -blessed => mkinst( 'Object' ) );

Example returns: abort:

    Hub::expect( -match => 'and|or|xor', 'if', 'or', 'and' );

Example returns: abort:

    Hub::expect( ARRAY => {} );

Example returns: abort:

    Hub::expect( -blessed => 'abc' );

Example returns: true:

    Hub::expect( -ref => 'HASH', {} );

Example returns: true:

    Hub::expect( -ref => 'HASH', mkinst('Object') );

fear

Croak if arguments match their feared type.

This is a shortcut to the expect manpage with a '-not=1' option.

Example returns: abort:

    Hub::fear( HASH => {} );

Example returns: true:

    Hub::fear( HASH => [] );

abort

Croak nicely.
 Usage: abort -msg => 'Croak message'
 Usage: abort -back => LEVEL

Example returns: abort:

    abort( -msg => 'Goddamn hippies' );

bestof

 Usage: bestof @list
 Usage: bestof @list, -by=max|min|def|len|gt|lt|true

Best value by criteria (default 'def').

min

Minimum value
 Usage: min @LIST

Returns the least element in a set.

Example: Two integers: (matches)

    Hub::min(1,2);
    1

Example: Three integers: (matches)

    Hub::min(2,1,3);
    1

Example: Three integers: (matches)

    Hub::min(2,-1,3);
    -1

Example: One integer: (matches)

    Hub::min(1);
    1

Example: Undefined value: (matches)

    Hub::min(1,undef);
    1

Example: Zero: (matches)

    Hub::min(undef,1,0);
    0

Example: Three decimal values: (matches)

    Hub::min(.009,1.001);
    0.009

max

Maximum value
 Usage: max @LIST

Returns the greatest element in a set.

Example: Three decimal values: (matches)

    Hub::max(.009,-1.01,2,undef,0);
    2

intdiv

Integer division
 Usage: intdiv $DIVIDEND, $DIVISOR

Returns an array with the number of times the divisor is contained in the dividend, and the remainder.

Example: 3 divided by 2 is 1R1: (matches)

    join(',',Hub::intdiv(3,2));
    1,1

flip

given a hash reference, swap keys with values and return a new hash reference.

rmval

Remove matching elements from a hash or an array.
 Usage: rmval \@array, $value
 Usage: rmval \%hash, $value

Example: (matches)

    join('',@{rmval([1,2,3,4],3)});
    124

cpref

Recursively clone the reference, returning a new reference.
 Usage: cpref ?ref
Implemented because the Clone module found on CPAN crashes under my mod_perl
and FastCGI test servers...

checksum

Create a unique identifier for the provided data
 Usage: checksum [params..]
Params can be scalars, hash references, array references and the like.

Example: (matches)

  my $x = 'like catfood';
  Hub::checksum( 'my', { cats => 'breath' }, ( 'smells', $x ) );
    2023611966

merge

Merge several hashes
 Usage: merge \%target, \%source, [\%source..], [options]

Merges the provided hashes. The first argument (destination hash) has precedence (as in values are NOT overwritten) unless -overwrite is given.

OPTIONS:

  -overwrite=1            Overwrite values as they are encounterred.
  -prune=1                Gives the destination hash the same structure as
                          the source hash (or the composite of all which is
                          in common when multiple source hashes are provided).
                          If the destination is missing a value, it is
                          initialized from the source hash.
                          If the destination has a value which is not in all
                          of the source hashes, it is deleted.

flatten

Get a consistent unique-by-data string for some data structure.
 Usage: flatten \%hash
 Usage: flatten \%array

replace

 Usage: replace MATCHING_REGEX, SUBSTITUTION_REGEX, TEXT

Do a s/// operation on a given segment of the string.

For example, say we want to remove the ': ;' pattern from the style portion, but not from the data portion:

  <div style="font-family: ;">keep this: ;stuff</div>

Use this method as:

  $text = Hub::replace( "style=\".*?\"", "s/[\\w\\-]+\\s*:\\s*;//g", $text );

digout

 Usage: digout REF, ID

Return an array of all nested values in an order that can be processed.

NOTE! Scalar values are returned as references.

See how 'packdata' uses this method to dereference.

Arrays are ignored unless their members are hashes with an _id member.

Reverse the results of this array to process data in a way that the children are affected before their parents.

diff

Creates a nest of the differences between the provided structures.
 Usage: diff \%hash1, \%hash2
 Usage: diff \@array1, \@array2

If a conflict of types (with the same key) is encounterred, the right-hand sturcture is used.

NOTE: Although this routine compares contents, it returns references to the original hashes (use the Hub::cpref manpage on the result to detatch.)

dice

Break apart the string into the least number of segments
 Usage: dice [options] $string
options:
  beg=$literal    Begin of balanced pair, Default is '{'
  end=$literal    End of balanced pair, Default is '}'

Example: (matches)

    join( ';', dice( "a{b{c}}c{d}" ) );
    a;{b{c}};c;{d}

indexmatch

Search for an expression within a string and return the offset
 Usage: indexmatch [options] $string, $expression, $position
 Usage: indexmatch [options] $string, $expression
Returns -1 if $expression is not found.

options: after 1|0 Return the position *after* the expression. Default is 0.

Example: (matches)

    indexmatch("abracadabra", "[cd]")
    4

Example: (matches)

    indexmatch("abracadabra", "a", 3)
    3

Example: (matches)

    indexmatch("abracadabra", "d{2,2}")
    -1

Example: (matches)

    indexmatch("scant", "can", "-after=1")
                - indexmatch("scant", "can")
    3

Top


INTERNAL METHODS

_assignopt

 Usage: _assignopt Assign an option value.
 Usage: _assignopt \%options, \%dest, $key, $val

_mergeHash

_mergeArray

_getId

_mergeElement

_diff_hashes

 Usage: _diff_hashes &HASH, &HASH

Difference between two hashes.

_diff_arrays

 Usage: _diff_arrays &ARRAY, &ARRAY

Difference between two arrays.

Top


AUTHOR

Ryan Gies (ryangies@livesite.net)

Top


COPYRIGHT

Copyright (C) 2006-2007 by Livesite Networks, LLC. All rights reserved.

Copyright (C) 2000-2005 by Ryan Gies. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

* Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

* The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

To the best of our knowledge, no patented algorithms have been used. However, we do not have the resources to carry out a patent search, and therefore cannot give any guarantee of the above statement.

Top


UPDATED

06/09/2007

Top