Read a series and add a value before and after that series.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Darshan S
    New Member
    • May 2015
    • 1

    Read a series and add a value before and after that series.

    I am very new to perl. Pls do help me out guys.

    I have a SAMPLE.txt file with values
    300000
    295000
    280000
    300000
    300000

    I need to read this file and over-write or creat a new file as below

    300000
    295000
    280000
    300000

    i.e. For values series other than 300000, add 300000 before and after the values as above.
  • computerfox
    Contributor
    • Mar 2010
    • 276

    #2
    How's this?

    Code:
    #!/bin/perl
    use strict;
    use warnings;
    
    sub gen(){
     my $path=shift;
     my $handler;
     my @rows;
     open($handler,"<",$path);
     while(<$handler>){
      my $row=$_;
      chomp($row);
      push(@rows,$row);
     }
     for(my $i=0;$i<$#rows;$i++){
      print $rows[$i]."\n";
      if($i>2){
       if($rows[$i] != "300000" && $rows[-2] != "300000"){
        print "300000\n";
       }
      }
     }
    }
    sub menu(){
     print "perl gen30.pl {input_file}";
    }
    if($#ARGV>-1){
     &gen($ARGV[0]);
    }
    else{
     print "Please provide the path to the input file...";
     print "\n";
     &menu();
    }
    You would run the script like this:
    Code:
    perl gen30.pl sample.txt > output.txt

    Comment

    • RonB
      Recognized Expert Contributor
      • Jun 2009
      • 589

      #3
      Your description of the desired output is a little vague.

      Given this file content:
      300000
      295000
      280000
      300000
      270000
      300000
      300000

      Should the output be:
      300000
      295000
      280000
      300000
      300000
      270000
      300000

      or should it be:
      300000
      295000
      280000
      300000
      270000
      300000

      Code:
      #!/usr/bin/perl
      
      use warnings;
      use strict;
      
      local $/ = "300000\n";
      
      while (<DATA>) {
          chomp;
          next if /^\s*$/;
          print "$/$_$/";
      }
      
      __DATA__
      300000
      295000
      280000
      300000
      270000
      300000
      300000

      Comment

      • RonB
        Recognized Expert Contributor
        • Jun 2009
        • 589

        #4
        FYI,
        Code:
          while(<$handler>){
          my $row=$_;
          chomp($row);
          push(@rows,$row);
         }
        Could be shortened and better written as:
        Code:
        chomp(my @rows = <$handler>);
        And:
        Code:
        for(my $i=0;$i<$#rows;$i++){
        is better written as:
        Code:
        for my $i (0 .. $#rows - 1) {

        Comment

        • computerfox
          Contributor
          • Mar 2010
          • 276

          #5
          Well noted Ron.
          Thanks.

          Comment

          Working...