in reply to Re: Parsing and adding to a "variable".
in thread Parsing and adding to a "variable".

Just expand out that one line expression so that you're saving the value of the number of paragraphs (i.e. by putting it into an array before putting it into $_content_to_add). Or I suppose you could just try: my $number_of_paragraphs = scalar (split /(?:\r?\n)+/, $_content_to_add);.

Replies are listed 'Best First'.
Re: Parsing and adding to a "variable".
by powerhouse (Friar) on Jan 25, 2004 at 00:24 UTC
    Most encouraging! Thank you Vautrin.... my $number_of_paragraphs = scalar (split /(?:\r?\n)+/, $_content_to_add); worked! It counted the number of pargraphs :o)

    Thanks again!!
    Richard
Re: Re: Re: Parsing and adding to a "variable".
by ysth (Canon) on Jan 25, 2004 at 05:40 UTC
    Whoa there, don't do that. split in scalar context will indeed return the number you want, but will have the side effect of replacing the contents of your @_ array. This unfortunate behaviour has been deprecated and will give a warning.
      Well then, what do you suggest I do?

      I don't know which @_ array your reffering too. In this line of code, I'm not using any arrays, I don't think.

      Please expand upon your comments. I would appreciate it.

      thx,
      Richard
        After thinking about it some, I don't like the way some of the solutions behave when you have \n at the end or beginning. To me, it would make more sense to ignore these. You can do that as a separate step, or integrate it in to the regex:
        my $paragraphs = $comments_to_add =~ s&(?=.*\S|\A)\s*(.*?)\s*?(?:\n(?!\r?\n)|\z)&<p>$1</p>&g;
        This assumes you want <p></p> even around an empty comment. If that's not the case, it's easier:
        my $paragraphs = $comments_to_add =~ s&\s*(.+?)\s*?(?:\n(?!\r?\n)|\z)&<p>$1</p>&g;
        I was dissatisfied with how complicated this turned out. If anyone has suggestions for making it simpler, I'd love to see.
        That's exactly the problem with split in scalar context. It does place the split up values into an array, @_, even though it doesn't appear to. Since @_ is also used for subs to access passed parameters, this is often a bug waiting to happen.

        Even if, in a particular case, you know overwriting @_ isn't a problem, it's a bad idiom to get into the habit of using.

        In your case, you could count paragraphs with m// instead (untested):

        my $paragraphs = 1 + (() = $_content_to_add =~ m/(?:\r?\n)+/g);
        or substitute <p>-stuff and count at the same time (also untested):
        my $paragraphs = 1 + $_content_to_add =~ s!(?:\r?\n)+!</p>\n<p>!g; $_content_to_add = "<p>$_content_to_add</p>";