begin_101 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm a new new-bee to Perl. I'm trying to convert my shell script to adapt to perl.

Please help me in building a regular expression for converting the below shell command `uuidgen | tr '\-abcdef' '9012345' | cut -c-10`

If the output of uuidgen is a81f9284-b353-430a-a8ce-85b8118d3f3e, I'm expecting it to print it as 0815928491. I tried with system('uuidgen') to generate the uuid, but unable to process it using the regular expression.

As tr does the translation and gives as 081592849135394300908249851811833534 and 'cut -c-10' gives the first 10 digits.

Cheers

Raj

Replies are listed 'Best First'.
Re: Help in building Regular expression
by toolic (Bishop) on Jan 17, 2012 at 20:14 UTC
    Here is one way, using tr and substr (without using regular expressions):
    use warnings; use strict; while (<DATA>) { tr/-abcdef/9012345/; print substr($_, 0, 10); print "\n"; } __DATA__ a81f9284-b353-430a-a8ce-85b8118d3f3e
    See also (documentation available at your command line via perldoc):

    To grab the output of an external command, such as uuidgen, you should use qx instead of system.

Re: Help in building Regular expression
by tobyink (Canon) on Jan 17, 2012 at 20:22 UTC

    You don't want system('uuidgen') here. system executes a command, but doesn't return the output of the command (it returns the command's exit status - the equivalent of $? in shell scripts). You want backticks.

    A fairly direct translation would be:

    my $string = `uuidgen`; $string =~ tr [\-abcdef] [9012345]; my $first_10 = substr($string, 0, 10);

    The tr operator (is it technically an operator? it's documented in perlop) acts much like the 'tr' command in many shells. substr extracts a substring from a string. The first argument is the string to extract from; the second argument is the character to start at (in this example, 0, so start at the beginning of the string) and the third is the number of characters to take (10 here). The third argument can be omitted, in which case substr extracts to the end of the string.

    A slightly better way though might be to avoid spawning the external program and use Data::UUID (or a similar module like UUID::Tiny).

    use Data::UUID; my $string = Data::UUID->new->create_str; $string =~ tr [\-abcdef] [9012345]; my $first_10 = substr($string, 0, 10);
    use UUID::Tiny; my $string = create_UUID(); $string =~ tr [\-abcdef] [9012345]; my $first_10 = substr($string, 0, 10);

      Thanks to toolic and tobyink, it worked like a charm!

      yes, tr/// (also known as y///) is the transliteration operator, much like m// is the match operator, and s/// is the substitution operator, and =~ is the binding operator
Re: Help in building Regular expression
by planetscape (Chancellor) on Jan 18, 2012 at 08:58 UTC