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.


In reply to Re: Printing Array with quote and comma by Tanktalus
in thread Printing Array with quote and comma by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.