[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 144
  • Last Modified:

Creatnig Dynamic Arrays

I have a string which I split into an array delimited by the underscore symbol;

my $string = d1156295_012424_PA01dc_ftxcv_ux12b1x0xxxxxxxxx_trctag_marchc_fy_cs_018
my @stringElements = split(/_/,$string);

I now whish to dynamically create an array with the name made up of two of the elements of @stringElements, i.e. $stringElements[0] and $stringElements[5] the array should be called @d1156295trctag.

I tried soing this:
my @{@stringElements[0]}.{@stringElements[5]}...but then how do I refer to it later??

I intend to fill this array with data and would like to eventually access the data by writing something like:

print @d1156295trctag[0]

How do I go about doing this and what it stuff referred to?

Thanks, - Troyh
  • 2
2 Solutions
What you look for is called "Symbolic References". It can be source of strange bugs, so use strict makes it illegal.
If you're sure that that is what you want, here is an example:

use strict;
use warnings;

# Your code
my $string = "d1156295_012424_PA01dc_ftxcv_ux12b1x0xxxxxxxxx_trctag_marchc_fy_cs_018";
my @stringElements = split(/_/,$string);

my $name = "$stringElements[0]$stringElements[5]";

print "$name\n";

# you have to disable "refs" strictness" in oreder to use
# symbolic reverences
no strict "refs";
push @{$name}, "Hello";
push @{$name}, "World";
${$name}[2] = "Bye";

print "${$name}[0] ${$name}[1]. ${$name}[2].\n";

# re-enable "refs" strictnes as soon as you can
use strict "refs";
#It's probably safer to
use strict;
my %name;
my $name=$stringElements[0].$stringElements[5];
@{$name{$name}} = qw(Hello World Bye);
print "@{$name{$name}}[0,1]. $name{$name}->[-1].\n";
It's the ongoing debate between safety and readablity.

Oh, and ny the way, Troyh, you probably mean
# printing Scalar
print $d1156295trctag[0]

# printing slice
print @d1156295trctag[0]

When printing single-element slice there's no visible difference, but there is.


Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now