in reply to Printing Array with quote and comma

Ok, I think you're looking at this just a bit off. Besides the excellent suggestions to not reinvent the wheel, I encourage you, if you're going ahead anyway, to solve the problem in the domain of the problem rather than in the domain of programming.

print "[", # leading bracket join(",", # items separated by commas map { "'$_'" } # each item surrounded by quotes @arr # the items ), "]\n"; # end bracket

The map is the part I think is important here. Your elements aren't actually what you have in the array - they are derived from what you have in @arr by adding quotes on each side. Then you join them, and put brackets around them.

The disadvantage here is that this probably takes up more memory than the other solutions. And is likely slower.

The advantage is that as you need to deal with more types, you can just handle them inside that map as appropriate by checking ref and dealing with the object as appropriate. Because the solution is in the same domain as the problem, it is more extendable inside that domain. For example, maybe a string has a special character that needs to be expanded - such as the carriage return "\n". In that case, you need to use double quotes rather than single quotes if you want the \n to appear as two characters that can be reinterpreted back to a single character later. The join solutions above don't allow for this because they're solving the problem in the domain of the programmer. The map solution allows that type of switch on an element-by-element basis.

Replies are listed 'Best First'.
Re^2: Printing Array with quote and comma
by ikegami (Patriarch) on Oct 05, 2005 at 04:41 UTC
    Same thing (well, better quoting), but possibly easier to read:
    sub bracket { local $_ = @_ ? $_[0] : $_; return "[$_]"; } sub quote { local $_ = @_ ? $_[0] : $_; s/(['\\])/\\$1/g; return "'$_'"; } print map { "$_;\n" } # Add tail. bracket # Surround with brackets. join ',', # Seperate elements with commas. map quote, # Quote elements. @arr; # Elements.
    or
    sub quote { local $_ = @_ ? $_[0] : $_; s/(['\\])/\\$1/g; return "'$_'"; } print map { "[$_];\n" } # Add brackets and tail. join ',', # Seperate elements with commas. map quote, # Quote elements. @arr; # Elements.