Perl

Perl:
($x, $y, $z) = "abc def ghi" =~ /^(.*?) (.*?) (.*?)$/;

Ruby:
(throwaway, x, y, z) = "abc def ghi".match(/^(.*?) (.*?) (.*?)$/).to_a

You know, sometimes, it’s just not the same.

Comments [+]

  1. You could also do

    x, y, z = "abc def ghi".scan(/^(.?) (.?) (.*?)$/)[0]

    By PatrickQG · 2007.02.16 00:08

  2. I know. The point - and I’m not sure everyone gets that; I’m actually not sure anyone gets that, including me - the point is: If you look at Ruby’s =~, it returns the substring index. Perl, on the other hand, can return two different values depending on the context in which it’s called, scalar or list context. “Why would you ever want to do that?” is a common question whenever that ability comes up. This is the answer.

    By Jesper · 2007.02.16 00:31

  3. Yet another solution:
    ruby -e ‘x, y, z = “abc def ghi”.match(/^(.*?) (.*?) (.*?)$/).captures; p x, y, z’

    By Jon · 2007.02.17 18:12

  4. Python:

    import re
    match = re.match('^(.*?) (.*?) (.*?)$', 'abc def ghi')
    x, y, z = re.groups()

    By Peter Hosey · 2007.02.18 07:09

Leave a comment

Your e-mail address is never shown. If you type a line break in the comment, it will show up as a line break (naturally). The following HTML is allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)


Please note: Your comment will not show up at once. Unless you're spamming or being abusive, you have nothing to worry about. (Read the full policy.)