in reply to Replacing, cutting, deleting lines in the file

A simple code snippet

#!/usr/bin/perl -w use strict; use warnings; use constant HANDLER => { 'line something starts here {' => sub{ return "Handler 1: do s +omethig with this data\n".shift;}, 'next block of something starts here {' => sub{ return "Handle +r 2: do somethig with this data\n".shift;}, # Other record Handlers }; # Read Records while (my $line = <DATA>){ chomp $line; next unless $line =~ /{/; my $header = $line; # READ HEADER # READ BODY $/="ends here }\n"; my $body = <DATA>; chomp $body; $/="\n"; print "Get Handler for: [$header]\n"; my $output = &{HANDLER->{"$header"}}($body); print $output if $output; } __DATA__ line something starts here { contains line 1 contains line 2 contains line 3 contains line 4 ends here } next block of something starts here { contains line 1 contains line 2 contains line 3 contains line 4 ends here }
«A contentious debate is always associated with a lack of valid arguments.»

Replies are listed 'Best First'.
Re^2: Replacing, cutting, deleting lines in the file
by Jarek (Novice) on Nov 24, 2009 at 14:38 UTC
    Hi, Thank you for your replies. And thank you for the code :). Anyway I will use it later when mine will be bad ;P. I've prepared something like:
    my $array_position; my $file = "/home/user/file.txt"; open FILE, $file; my @file = (<FILE>); close FILE; foreach ( @file ) { if ($_ =~ /line 3/) { $array_position=$i+1; print "Position in array = ". $array_position. "\n"; } $i++; } for ($a=$array_position-1; $a<$array_position+3; $a++) { print "Postion ".$a." in the array = " .$file[$a]; } @array = @file; splice @array, 0, 'something'; print @array;
    The file.txt contains this:
    line 1 line 2 fsefse line 3 line 4 ,... line 5 line 6>
    The problem is it doesn't want to replace first element from the array to string I specified. Any ideas why ? Regards, Jarek
      Is this what you want?
      use strict; use warnings; use Data::Dumper; my @file = (<DATA>); my @array = @file; splice @array, 0, 1,'something'; print Dumper \@array; __DATA__ line 1 line 2 fsefse line 3 line 4 ,... line 5 line 6>
        Yes, Thank you. Can you explain me why you had to put two parameters 0, 1 to replace only the first element ? OK... :) I know why... thank you :) Regards, Jarek