Module:...Dynamic(3)
π NAME π
Okay so bestie, welcome to the Module:...Dynamic(3) page from User Contributed Perl Documentation. The main character here is Module::Generic::Dynamic, aka the Dynamic Object Class. Itβs giving βbuild objects on the flyβ energy, and weβre gonna walk through it together π«Ά
β¨ SYNOPSIS β¨
package My::Module;
use parent qw( Module::Generic::Dynamic );
# Then, instantiating an object
my $object = My::Module->new({
name => 'Test Product',
quantity => 20,
metadata => { sku => 'ABC123', price => 99.99 },
tags => [qw( product entrepreneurship capital )],
created => '2023-11-18T10:30:00',
is_active => 1,
url => 'https://example.com',
file_path => './config.ini',
});
# Accessing methods
print $object->name; # Test Product
print $object->metadata->sku; # ABC123
print $object->tags->join(','); # product,entrepreneurship,capital
print $object->created->year; # 2023
# Dynamic method creation via AUTOLOAD
$object->version('1.2.3');
print $object->version->stringify; # 1.2.3
π VERSION π
v1.3.0 β yes bestie, thatβs the version π
π¦ DESCRIPTION π¦
Module::Generic::Dynamic provides a framework for dynamically creating classes and methods based on an input hash reference. It automatically generates accessor methods for each key-value pair, inferring the appropriate data type and handling method creation at runtime using AUTOLOAD.
This module is particularly useful for creating flexible, data-driven objects where the structure is not known in advance. It supports a wide range of data types, including scalars, hashes, arrays, booleans, URIs, UUIDs, IP addresses, versions, files, code references, globs, and custom objects.
For more granular control over the method to be used for each data key-value, use _set_get_class in Module::Generic.
π METHODS π
β¨ new β¨
Provided with a hash reference of data, this creates a new object and dynamically generates a class based on the calling package name. For each key-value pair in the hash, it creates an accessor method and assigns an appropriate handler based on the data type:
arrayβ If the array contains hash references, creates a method using_set_get_object_array_objectin Module::Generic with a new dynamic class for each hash element. Otherwise, uses_set_get_array_as_objectin Module::Generic to return aModule::Generic::Arrayobject.booleanβ For keys matchingis_,has_,enable,active,valid,disabled, orinactive(case-insensitive) with values0,1,undef, or empty string, uses_set_get_booleanin Module::Generic to return aModule::Generic::Booleanobject.codeβ For code references, uses_set_get_codein Module::Generic to store and execute the code.fileβ For keys matchingfileorpathwith a valid file path (e.g.,./config.ini,~/docs), uses_set_get_filein Module::Generic to return aModule::Generic::Fileobject.globβ For glob references (e.g., filehandles), uses_set_get_globin Module::Generic.hashβ Creates a method using_set_get_objectin Module::Generic and a new dynamic class (e.g.,My::Module::KeyName) for nested hash data.integerβ For keys matchingcount,size, orquantitywith an integer value, uses_set_get_numberin Module::Generic to return aModule::Generic::Numberobject.- IP address β For keys matching
ip,ip_addr, orip_addresswith a valid IPv4 or IPv6 address, uses_set_get_ipin Module::Generic to return aModule::Generic::Scalarobject. numberβ For numeric values (integer or floating-point), uses_set_get_numberin Module::Generic to return aModule::Generic::Numberobject.objectβ For blessed objects (e.g.,JSON::PP::Boolean,Module::Generic::File, custom classes), uses the appropriate handler (e.g.,_set_get_booleanin Module::Generic for booleans) or_set_get_objectin Module::Generic for others, preserving the objectβs class.stringβ Creates a method using_set_get_scalar_as_objectin Module::Generic, returning aModule::Generic::Scalarobject.URIβ For keys matchinguriorurlor values starting withhttp://orhttps://, uses_set_get_uriin Module::Generic to return aURIobject. IfRegexp::Common::URIis available, it validates URIs more precisely.UUIDβ For keys matchingid,_id, or ending withidwith a valid UUID format, uses_set_get_uuidin Module::Generic to return aModule::Generic::Scalarobject.versionβ For keys matchingversionwith a valid version string (e.g.,1.2.3), uses_set_get_versionin Module::Generic to return a version object.
If a key results in an invalid method name (e.g., starting with digits), it is sanitized by removing non-alphanumeric characters and leading digits.
Example:
my $obj = Module::Generic::Dynamic->new({
name => 'Test',
is_active => 1,
url => 'https://example.com',
file => './config.ini',
});
print $obj->name; # Test
print $obj->is_active; # 1 (Module::Generic::Boolean)
print $obj->url->host; # example.com
print $obj->file->basename; # config.ini
π AUTOLOAD π
Dynamically creates accessor methods for undefined method calls based on the method name and the first argumentβs type (if provided). It uses the same type-guessing logic as new, inferring handlers from:
- Method name patterns (e.g.,
is_activefor boolean,urlfor URI). - Argument types (e.g.,
JSON::PP::Boolean, hash, array, scalar). - Value formats (e.g., UUID, IP address, file path).
If no arguments are provided (getter call), the method is created based on the method name. For example:
my $obj = Module::Generic::Dynamic->new;
$obj->url('https://example.com');
print $obj->url->host; # example.com
print $obj->is_active; # Creates boolean accessor, returns undef
Invalid inputs (e.g., non-UUID values for id fields) fall back to _set_get_scalar_as_object in Module::Generic.
π SERIALISATION π
Serialisation is supported for CBOR, Sereal, Storable::Improved, and Storable. The module implements FREEZE, THAW, STORABLE_freeze, STORABLE_thaw, and TO_JSON to handle object serialization and deserialization, preserving data types and structure.
Example:
my $obj = Module::Generic::Dynamic->new({ name => 'Test', tags => [qw( product test )] });
my $data = $obj->serialise( $obj, serialiser => 'Storable::Improved' );
my $new_obj = Module::Generic->new->deserialise( data => $data, serialiser => 'Storable::Improved' );
print $new_obj->name; # Test
print $new_obj->tags->join(','); # product,test
π THREAD SAFETY WARNING π
This module is not thread-safe. No cap.
Module::Generic::Dynamic dynamically creates packages and injects methods into symbol tables at runtime using eval. In multi-threaded environments (Perl ithreads), this can cause:
- Race conditions between threads attempting to create the same symbol.
- Corrupted symbol tables if a method is installed while another thread is reading or writing from the same class.
π«Ά Recommended Usage π«Ά
- Use this module only during application initialization, before any threads are spawned.
- Avoid invoking
newor triggeringAUTOLOADfrom within a thread. - In persistent environments (e.g.,
mod_perl), precompile structures at startup.
π ERROR HANDLING π
Errors in new and AUTOLOAD, such as invalid parameters or failed method creation, return undef with an error object accessible via $obj->error. Check for errors to handle failures gracefully:
my $obj = Module::Generic::Dynamic->new({ name => 'Test' });
die $obj->error if !defined $obj;
Invalid method names (e.g., starting with digits) are sanitised by removing non-alphanumeric characters and leading digits, or ignored if no valid name remains.
π LIMITATIONS π
- Invalid method names (e.g.,
123invalid) are sanitised or ignored, which may lead to unexpected behavior if not checked. - Type guessing is conservative to avoid false positives. For example, a string like
/api/v1is treated as a scalar unless the key name suggests a file (e.g.,file_path). - Ambiguous inputs (e.g., a number that could be a version or integer) may default to a less specific handler (e.g.,
_set_get_numberin Module::Generic).
Users can override type guessing by explicitly using _set_get_class in Module::Generic for more control.
πΈ AUTHOR πΈ
Jacques Deguest β jack@deguest.jp π«Ά
π COPYRIGHT & LICENSE π
Copyright (c) 2000-2024 DEGUEST Pte. Ltd.
You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
Mwah π β this page comes from perl v5.42.2, dated 2026-02-15, and itβs the Module:...Dynamic(3) page. Bye bestie! π«Ά
π¦ where this page comes from
- alpine 3.24: perl-module-generic-doc 1.1.3-r1 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms