in reply to clean code

I pretty much like what you have already! It's easy to understand and robust. The only thing I think you really ought to change are the backslashes in the split regexes, which shouldn't be there.

All the other changes I'd make are superficial. Structurally, the temporary variable @vals can be eliminated by putting it within the loop initializer. Stylistically, I think you ought to leave off the comment marking the end of the loop, as you're already practicing proper indentation, and that's sufficient. Here's some code I might have written:

# extract name-value pairs from serialized database row for my $pair ( split( /;/, $serialized_row ) ) { my ( $name, $value ) = split( /=/, $pair ); $record{$name} = $value; }
--
Marvin Humphrey
Rectangular Research ― http://www.rectangular.com

Replies are listed 'Best First'.
Re^2: clean code
by sfink (Deacon) on Apr 23, 2006 at 05:42 UTC
    Make that split(/=/, $pair, 2) and your values will be allowed to have equals signs.

    For most casual applications, I usually use split(/\s*=\s*/, $pair, 2). I like spaces. I'd do the same for the semicolon split. But considering the comment (this is from a serialized db row), I doubt there's much point.

    To be more robust (specifically: to allow arbitrary characters in the names and values), I agree with the suggestions to use URI escaping. Since you're programmatically generating the data you're parsing, there's no reason not to do the job right -- your first concern should be correctness, second should be basic human readability (so you can tell what's going on), and a very distant third should be human writability (for debugging, casual testing, off-the-cuff model manipulation, etc.)

      sfink++ on the additional argument to split().

      As for the comment, the original post did not make clear the purpose of the code block. I always code in commented paragraphs (as per Perl Best Practices), and such comments should be as specific as possible. However, I didn't want to make a big deal about that personal stylistic choice it because it wasn't germane.

      Several other posters made what I think was a reasonable assumption that the purpose of the block was CGI processing, presumably based on the structure of the data and the name of the $memory_data variable. Processing of CGI query strings raises a host of issues I didn't want to get into, so I made a different assumption about the nature of the data. :)

      --
      Marvin Humphrey
      Rectangular Research ― http://www.rectangular.com