Assign scalar value to array

by paramreddy (Initiate)
 on Oct 09, 2013 at 14:17 UTC Need Help??
paramreddy has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, Hope all of you having good time. I am new to perl and i am trying to learn perl. Here i want to know whether we can assign scalar value to array. example \$num=12345; and i want 12345 should be assigned to @a @a = qw\1 2 3 4 5\ Can you help me in this? Thanks in advance, Parameshwar

Replies are listed 'Best First'.
Re: Assign scalar value to array
by ikegami (Pope) on Oct 09, 2013 at 14:21 UTC
```@a = split //, \$num;
Re: Assign scalar value to array
by flyby (Acolyte) on Oct 09, 2013 at 23:24 UTC

Just some fun:

```#!/usr/bin/perl -w

my @a;
my \$num = "12345";

# most likely the best way to do it:

@a = split(//,\$num);

foreach (@a) {
print "\$_\n";
};

# but this is kind of fun:

@a = (); #clear array

my \$l = length(\$num);

for (my \$x = "0"; \$x < \$l; \$x++ ) {
push(@a, substr(\$num, \$x, 1));
};

foreach (@a) {
print "\$_\n";
};

# random:

@a = (); #clear array

for (my \$x = "0"; \$x < \$l; \$x++ ) {
my \$rand = rand(\$l);
push(@a, substr(\$num, \$rand, 1));
};

foreach (@a) {
print "\$_\n";
};

-Matt

Re: Assign scalar value to array
by Anonymous Monk on Oct 09, 2013 at 22:01 UTC
```\$num = 12345;
# empties the array
@a = (\$num);
# or
\$a[0] = \$num;

print '\$a[0] is ', \$a[0], "\n";

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1057552]
Approved by Corion
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2018-01-22 02:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (230 votes). Check out past polls.

Notices?