#!/usr/bin/perl -l # https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order use strict; use warnings; $_ = 'aabbcc'; 1 while print, s/.*\K # find the last (.) # char such that (.*) # there is a later (latest) (.)(??{$1 ge $3 and '(*F)'}) # char greater than it (.*) # and get rest # swap those two chars ( $1 & $3 ) # then reverse everything after the first swapped char / $3 . reverse $2.$1.$4 /xe