http://www.perlmonks.org?node_id=1057552

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 (Patriarch) on Oct 09, 2013 at 14:21 UTC
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";