SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    perl script to add information to a file.

    Hi,
    i have one hash tables that contains data stings and information. I have one c file , i need to search the file and if i found stings in the c file i need to add information at the top of the c file. I am very beginer to perl, i have written code like this
    code:
    #!/usr/bin/perl
    use warnings;
    use strict;

    open (my $code , "<", 'c.c');

    my %strings = ('string1'=>"information \n",
    'string2'=>"information2 \n",
    'string3'=>"information3 \n",
    );


    my $test_string="(" .join("|", keys %strings).")" ;

    while(<$code>){

    if (/$test_string/){

    chomp;


    $_.=$strings{$1};
    }
    print $_
    }

    this code adding the information before the string, i need to add at the top of the c file. what should i do in this case.

  2. #2
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sadly, there's no way to insert information at the beginning of a file without having to rewrite the whole thing, so you'll need to read in the entire file (rather than just one line at a time), determine which string(s) appear in the contents, write the corresponding information item(s) to a new file, and (finally!) write the original contents to the new file:

    Code:
    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use File::Slurp;
    
    my %strings = (
      'string1' => "information \n",
      'string2' => "information2 \n",
      'string3' => "information3 \n",
    );
    my $test_string = "(" . join("|", keys %strings) . ")";
    
    # First make a list of all matched strings (including the number of times
    # each was found, although I assume that's not actually relevant)
    
    my $code = read_file('c.c');
    my %found;
    while ($code =~ /$test_string/g) {
      $found{$1}++;
    }
    
    # If %found is empty, we didn't find anything to insert, so no need to rewrite
    # the file
    
    exit unless %found;     
    
    # Write the prefix data to the new file followed by the original contents
    
    open my $out, '>', 'c.c.new';
    for my $string (sort keys %found) {
      print $out $strings{$string};
    }
    
    print $out $code;
    
    # Replace the old file with the new one
    rename 'c.c.new', 'c.c';

  3. #3
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,
    thanks for your reply, i will try like this .


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •