Posted on 2006-11-02 10:40:00-08 by berislav
Printing shuffled string
Hello Jerry, First of all, my apologies for bothering you with this newbie question regarding MRMA module. How exactly can I get the shuffled string to print nicely on screen? I have written the following code:
print "Enter string: "; $string=<STDIN>; chomp $string; $string_shuffled=shuffle($string); print "\nOriginal: ", $string; print "\n\nShuffled: ", $string_shuffled, "\n"; exit;
And the output I get isn't reshuffled string, but something like ARRAY(0x88982fc) Thanks very much in advance! Berislav
Direct Responses: 3413 | Write a response
Posted on 2006-11-02 13:37:08-08 by jdhedden in response to 3411
Re: Printing shuffled string
From the POD:
shuffle my $shuffled = shuffle($data, ...); my $shuffled = shuffle(@data); my $shuffled = shuffle(\@data); Returns an array reference containing a random ordering of the supplied arguments (i.e., shuffled) by using the Fisher-Yates shuffling algorithm. If called with a single array reference (fastest method), the contents of the array are shuffled in situ.
The shuffle command takes a list/array or array ref, and returns the mixed results inside an array ref.

Strings are not arrays. If you want to shuffle the 'components' of a string you need to split it in some manner.
#!/usr/bin/perl use strict; use warnings; use Math::Random::MT::Auto qw(shuffle); MAIN: { print 'Enter string : '; my $string = <STDIN>; chomp($string); # Shuffle characters my @chars = split('', $string); my $shuffled_chars = shuffle(@chars); print('Shuffled chars: ', @{$shuffled_chars}, "\n"); # Shuffle words my @words = split(' ', $string); my $shuffled_words = shuffle(@words); print('Shuffled words: ', join(' ',@{$shuffled_words}), "\n"); } print("Done\n"); exit(0);
Direct Responses: Write a response
Perl Weekly newsletter
A free weekly newsletter for people who are busy to read all the blogs. click here to check it out.