On Tue, Nov 3, 2009 at 12:11 AM, Majian <[email protected]> wrote:
> Hi ,all :
>
> I want to know if there is a way in which I can randomnize(?) the content
> in
> an array.
>
> In this example :
>
> my @array = ('uriel', 'daniel', 'joel', 'samuel');
>
> Now what I want is create a process so every time I print the array it
> prints one element from the array .
>
> I wrote it like this :
>
> #!/usr/bin/perl -w
>
> use strict;
>
> my @array = ('uriel', 'daniel', 'joel', 'samuel');
> print "Array before random: @array\n\n";
>
> print "Array of random: $array[rand @array]\n";
>
>
> I thoght it might work but it doesnt. I hope someone could give me an
> idea to work this out...
>
The op's code works for me:
$ perl -v
This is perl, v5.8.6 built for darwin-thread-multi-2level
(with 3 registered patches, see perl -V for more detail)
Copyright 1987-2004, Larry Wall
<snip>
$ cat 1perl.pl
#!/usr/bin/perl -w
use strict;
my @array = ('uriel', 'daniel', 'joel', 'samuel');
print "Array before random: @array\n\n";
print "Array of random: $array[rand @array]\n";
$ 1perl.pl
Array before random: uriel daniel joel samuel
Array of random: uriel
$
...but I would be afraid to put such a complex variable name inside a
string. I read somewhere that you can put { } around just the part of a
string that you want perl to use as the variable name. For instance,
instead of this:
my $str = "hello ";
my $result = "$strworld";
print $result, "\n"
--output:--
Global symbol "$strworld" requires explicit package name at 1perl.pl line 5.
Execution of 1perl.pl aborted due to compilation errors.
...you can write this:
use strict;
use warnings;
my $str = "hello ";
my $result = "${str}world";
print $result, "\n"
--output:--
hello world
Maybe putting braces around the op's variable name might be applicable? For
instance,
print "Array of random: ${array[rand @array]}\n";