in reply to Re^3: Adding hashes to already existing array
in thread Adding hashes to already existing array

I apologize. I do use strict and warnings. That and any typos I have are because I do not have perl on this system and have to look at the other system where I test it to type it here.

I would agree that the syntax I have is not what I want. As I mentioned in my reply to stevieb, a normal AoH syntax would have been better.

If I understand what you have, you get the strings into $excerpts[$i], then replace those strings with hashes in the

$excerpts[$i] = { fpart=>$1, bpart=>$3 };
step. This unfortunately gets rid of the original string in each array element. I could get around this by doing
$excerpts[$i] = { fpart=>$1, bpart=>$3, content=>$value };
if I first get the content into $value before overwriting it.

Thanks

Replies are listed 'Best First'.
Re^5: Adding hashes to already existing array
by poj (Abbot) on May 06, 2016 at 20:26 UTC
    #!perl use strict; use Data::Dump 'pp'; my @excerpts = (); my $fc = 'abcdfoofrobnicatebardefforspambazghi'; my $re2 = qr/(fo.)(.*?)(ba.)/; while ($fc =~ /$re2/g){ push @excerpts, { fpart => $1, bpart => $3, content => $1.$2.$3 } ; } pp @excerpts;
    poj
Re^5: Adding hashes to already existing array
by haukex (Archbishop) on May 06, 2016 at 20:32 UTC

    Hi ExReg,

    if I first get the content into $value before overwriting it

    $excerpts[$i] = { fpart=>$1, bpart=>$3, content=>$excerpts[$i] }; will do what you want.

    Hope this helps,
    -- Hauke D

      Exactly what I wanted

        You should always check to ensure you have a match. Either use while(), or:

        for my $i (0.. $#excerpts){ if (excerpts[$i] =~ /$re2/({ $%{$excerpts[$i]}{fpart} = $1; $%{$excerpts[$i]}{bpart} = $3; } }

        ...or you may get undef warnings, or unexpected results that you'll be head-scratching at, because the numbered variables hold their values in a loop, until overwritten. Example:

        perl -wE '@a=(1,2,3); for(@a){/(2)/; say $1}' Use of uninitialized value $1 in say at -e line 1. 2 2

        In the third iteration, we don't match /2/ at all, yet $1 still has the value from the last time it was captured.