The get method in Hash::Lookup provides a way to retrieve values from deeply nested data structures using a query string. The query language resembles JSON Pointer, jq, or JPath and supports accessing hashes and arrays through dot (.) notation and bracket ([]) notation.
The query string consists of key names separated by dots (.) or array indices specified numerically. The following conventions apply:
.): Used to navigate through nested hash keys.N): Used to access specific elements in arrays.[]): Used to extract values from all array elements.,): Allows retrieving multiple values at once..)Dot notation allows accessing nested hash keys. For example:
$data->get(“level1.level2.level3”); # Retrieves $data->{level1}->{level2}->{level3}
undef is returned.undef.N)When an array is encountered, an integer index retrieves a specific element:
$data->get(“level1.array_key.1.sub_key”); # Retrieves $data->{level1}->{array_key}->[1]->{sub_key}
When an hash is encountered, an integer index is treated as a key and retrieves a specific element:
$data->get(“level1.array_key.1.sub_key”); # Retrieves $data->{level1}->{array_key}->{“1}”->{sub_key}
undef.undef.[])When an array is encountered, using [] retrieves values from all elements of the array:
$data->get(“level1.array_key.[].sub_key”); # Retrieves all sub_key values in array
When a hash is encountered, using [] retrieves all the values from the hash:
$data->get(“level1.array_key.[].sub_key”); # Retrieves all sub_key values in array
$data->get("level1.array_key.[]") returns the entire array.$data->get("level1.array_key.[]") returns all the values in the hash.,)A comma-separated query retrieves multiple values at once:
$data->get(“level1.level2.level3,another_key”);
This returns an array containing both values.
$data->get("[].key") retrieves key from all hash elements.$data->get("[]") returns the array of hash elements as-is.| Query | Result |
|---|---|
"foo.bar" (non-existent key) |
undef |
"arr.foo" (string index on array) |
undef |
"arr.5" (out-of-bounds index) |
undef |
".foo.bar." (leading/trailing dots) |
undef |
{} (empty hash) with any key |
undef |
"" (empty string) |
Returns whole structure |
| Scalar base structure | undef |
| Circular references | Returns circular reference |