PetreAdi has asked for the wisdom of the Perl Monks concerning the following question:

How do I extract the first 2 elements of an array and add to end

__DATA__

1234

5678

1000

1233

$file="abc.txt"; open (DAT, "<$file")|| die("Cannot Open File"); @array = <DAT>; close (DAT);

The output should be:

print @newarray

123412

567856

100010

123312

Replies are listed 'Best First'.
Re: Array manipulation
by kschwab (Vicar) on Nov 04, 2013 at 18:21 UTC
    #!/usr/bin/perl while(<>) { chomp; print $_ . substr($_,0,2) . "\n"; }

    Accepts files either from standard input, or named on the command line, iterates over each line, prints with the first two characters (of each line) repeated at the end of the line.

Re: Array manipulation
by 2teez (Vicar) on Nov 04, 2013 at 18:15 UTC

    Something like this can do:

    use warnings; use strict; while(<DATA>){ chomp; print $_,substr ($_,0,2),$/; } __DATA__ 1234 5678 1000 1233


    NOTE:I updated the code, since I was testing on an old Perl version before now.
    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
Re: Array manipulation
by Anonymous Monk on Nov 05, 2013 at 03:41 UTC

    Maybe a substitution:

    print s/^(\d\d)\d*\K/$1/r while <DATA>;
Re: Array manipulation
by BillKSmith (Monsignor) on Nov 05, 2013 at 04:33 UTC
    Your question has nothing to do with arrays. You should have asked "How can I append a copy of the first two characters of a string to the end of that string?"
    Bill
Re: Array manipulation
by johngg (Canon) on Nov 05, 2013 at 10:35 UTC

    Another way is to use the four argument form of substr rather than concatenation.

    $ perl -Mstrict -Mwarnings -E ' open my $inFH, q{<}, \ <<EOD or die $!; 1234 5678 1000 1233 123456 EOD say for map { chomp; substr $_, length, 0, substr $_, 0, 2; $_; } <$inFH>;' 123412 567856 100010 123312 12345612 $

    I hope this is helpful.

    Cheers,

    JohnGG