Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??
Sorry, I am very frustrated right now. I have spent the last six hours trying to come up with a simple perl program to list all permutations for the numbers from one to five (the use of cpan modules is not allowed for this exercise).

The well-known algorithm and code snippets in other languages can be found here:

One python implementation is very brief and almost understandable (though my python knowledge is even poorer than my perl knowledge):

def permute(in_str, prefix=""): if not len(in_str) : print(prefix) else: for i in range(0, len(in_str)): permute(in_str[:i] + in_str[i + 1:], prefix + in_str[i]) permute('12345')
The biggest problem is (even after reading man perlsub for over an hour), I just don't understand the calling syntax. My attempt is looking something like this (which generates a huge number of syntax errors and won't run).
#!/usr/bin/perl -w use strict; my @array = 1..5; while (permute @array) sub permute { my @temp; while ( $#temp < $#_) { my $i; for ($i = $#temp; $i < $#_; $i++) { swap @_[$i] @_[$#temp]; permute; swap @_[$i] @_[$#temp]; } } print $_; } sub swap { my $k; my $l; my $temp; $temp = $k; $k = $l; $l = $temp; }

Can someone guide me in the right direction. Clever techniques are not important. What is important is that I understand what is going on.

Thank you (very much) in advance.

In reply to generating permutations by Anonymous Monk

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.