1

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!

1
  • I'm having a bit of trouble figuring out what kind of datastructure you want to have in the end. Hash of arrays? Hash of hashes? Can you elaborate? c.f. perldsc. Commented Nov 1, 2014 at 5:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 ]];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.