Home > Enterprise >  Split the string and append the second and first elements
Split the string and append the second and first elements

Time:11-22

I am new to perl scripting. tried following code

#!/usr/bin/perl -w
our $sep = "-";

open my $data, $ARGV[0] or die "Can't open $ARGV[0] for reading: $!";
while( my $line = <$data> )
{
        $line =~ s/]:/\n]:/g;
        my @spl = split(', ', $line);
        $hello = $spl[2].'-'.$spl[1];
        print $hello;
        print "\n";
}

My sample input

, 1234, task]: 1122

My current output

task
]: 1122
-1234

My expected sample output

task-1234]: 1122

CodePudding user response:

The desired result can be achieve in many ways. Perhaps split is not the best approach in this particular case.

Input sample data have very simple format and can be processed with regex.

use strict;
use warnings;
use feature 'say';

my($fname,$regex);

$regex = qr/^, (\d ), (. ?)]: (\d )$/;

while( <DATA> )
{
    next if /^\s*$/;
    my @data = $_ =~ /$regex/;
    say "$data[1]-$data[0]\]: $data[2]";
}

exit 0;

__DATA__
, 1234, task]: 1122

Output

task-1234]: 1122

Note: replace <DATA> with <> to process a file specified on command line

Following code sample utilizes split to achieve same result

use strict;
use warnings;
use feature 'say';

while( <DATA> )
{
    next if /^\s*$/;
    my @data = split(/[, \]:] /, $_);
    say "$data[2]-$data[1]\]: $data[3]";
}

exit 0;

__DATA__
, 1234, task]: 1122

Output

task-1234]: 1122

You can start learn Perl by Google search Perl bookshelf, although books are dated they still of great value.

Please look at following free book to get upto date programming style

There are plenty free perl programming books available on the internet.

CodePudding user response:

I am able to solve it, But logic is too bad

open my $stack, $ARGV[0] or die "Can't open $ARGV[0] for reading: $!";
while( my $line = <$stack> )
{
        my @spl = split(']:', $line);
        my @spl1 = split(', ', $spl[0]);
        $line = $spl1[2].'-'.$spl1[1]."]:".$spl[1];
        print $line;
        print "\n";
}

Expected output

task-1234]: 1122
  • Related