Reputation: 47
Can anybody please let me know how can I make an array ref out of a scalar variable (equivalent to a hash ref)? The code I have so far is:
#! /usr/bin/perl
use strict;
my $index=0;
my $car={};
$car->{model}[$index]="Tesla";
my $texxt = $car->{model}[$index];
@{$texxt}=qw(1 2 3);
print "@{$texxt}";
This gives the following error: Can't use string ("Tesla") as an ARRAY ref while "strict refs" in use at test99.pl line 8.
Basically I am trying to make an array (or an array ref) called "@Tesla" that has values (1 2 3).
Thanks for your help!
Upvotes: 1
Views: 174
Reputation: 6378
If you want a hash with a key called "model" that contains an array with "Tesla" as the first element and an anonymous array as the second element (and texxt
as a short cut reference to that) then this would work
#! /usr/bin/perl
use strict;
my $index=0;
my $car={};
$car->{model}[$index]="Tesla";
my $texxt = $car->{model} ;
push @{$texxt} , [qw(1 2 3)];
print ref eq "ARRAY" ? "@{$_}" : "$_ " for @{$texxt} ;
output: Tesla 1 2 3
You can use Data::Printer
to view the data structure in a nicely formatted way:
use DDP;
p $texxt;
outputs:
\ [
[0] "Tesla",
[1] [
[0] 1,
[1] 2,
[2] 3
]
]
This can help you visualize what perl is doing to your data.
Upvotes: 1
Reputation: 241818
If $texxt is a string (it's not a hash ref), you cannot dereference it as an array. You can assign an anonymous array to it, though:
$texxt = 'Tesla';
$texxt = [qw[ 1 2 3 ]];
Upvotes: 0