Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9130891
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:02:54+00:00 2026-06-17T08:02:54+00:00

I want my perl program to do the substitution of ‘{‘ – > ‘{function(‘.counter++.’)’

  • 0

I want my perl program to do the substitution of ‘{‘ – > ‘{function(‘.counter++.’)’ in all the files except the lines when there is a ‘{‘ and a ‘}’ in the same line, and except when the ‘{‘ appears one line under a ‘typedef’ substring.

#!/usr/bin/perl

use strict;
use warnings;
use Tie::File;
use File::Find;

my $dir = "C:/test dir";   


# fill up our argument list with file names:
find(sub { if (-f && /\.[hc]$/) { push @ARGV, $File::Find::name } }, $dir);

$^I = ".bak";   # supply backup string to enable in-place edit 

my $counter = 0; 

# now process our files 
while (<>) 
{
    my @lines;
    # copy each line from the text file to the string @lines and add a function call after every '{' '
    tie @lines, 'Tie::File', $ARGV or die "Can't read file: $!\n"

    foreach  (@lines) 
    {   
        if   (!( index (@lines,'}')!= -1 )) # if there is a '}' in the same line don't add the     macro
            {
                s/{/'{function(' . $counter++ . ')'/ge;
                print;
            }

    }
    untie @lines; # free @lines
}    

what I was trying to do is to go through all the files in @ARGV that i found in my dir and subdirs and for each *.c or *.h file I want to go line by line and check if this line contains ‘{‘. if it does the program won’t check if there is a ‘{‘ and won’t make the substitution, if it doesn’t the program will substitute ‘{‘ with ‘{function(‘.counter++.’);’

unfortunately this code does not work. I’m ashamed to say that I’m trying to make it work all day and still no go.I think that my problem is that I’m not really working with lines where I search for ‘{‘ but I don’t understand why. I would really appreciate some help.

I would also like to add that I am working in windows environment.

Thank You!!

Edit: so far with your help this is the code:

use strict;
use warnings;
use File::Find;

my $dir = "C:/projects/SW/fw/phy";   # use forward slashes in paths

# fill up our argument list with file names:
find(sub { if (-f && /\.[hc]$/) { push @ARGV, $File::Find::name } }, $dir);

$^I = ".bak";   # supply backup string to enable in-place edit 

my $counter = 0; 

# now process our files
while (<>) {
    s/{/'{ function(' . $counter++ . ')'/ge unless /}/;
    print;
}

The only thing that is left to do is to make it ignore ‘{‘ substitution when it is one line under ‘typedef’ substring like this:

typedef struct 
{
}examp;

I would greatly appreciate your help! Thank you! 🙂

Edit #2: This is the final code:

use strict;
use warnings;
use File::Find;

my $dir = "C:/exmp";   

# fill up our argument list with file names:
find(sub { if (-f && /\.[hc]$/) { push @ARGV, $File::Find::name } }, $dir);

$^I = ".bak";   # supply backup string to enable in-place edit 

my $counter = 0; 
my $td = 0;

# now process our files
while (<>) {
    s/{/'{ function(' . $counter++ . ')'/ge if /{[^}]*$/ && $td == 0;
    $td = do { (/typedef/ ? 1 : 0 ) || ( (/=/ ? 1 : 0 ) && (/if/ ? 0 : 1 ) && (/while/ ? 0 : 1 ) &&             (/for/ ? 0 : 1 ) && (/switch/ ? 0 : 1 ) )}; 
    print;
}

The code does the substitution except when the line above the substitution place included ‘typedef’,
When the line above it included ‘=’ and no ‘if’, ‘while’, ‘for’ or ‘switch’ the substitiution will also not happen.

Thank you all for your help!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:02:55+00:00Added an answer on June 17, 2026 at 8:02 am

    The -i swith let you presise an extension for backup files.

    Using perl:

    perl -pe "/{[^}]*\$/&&do{s/{/{function('.counter++.');/}" -i.bak *
    

    or (same result):

    perl -pe "s/{/{function('.counter++.');/ if /{[^}]*\$/" -i.bak *
    

    And for processing all files in sub-folder too, this could be simplier to use find:

    find . -type f -print0 |
        xargs -0 perl -pe "s/{/{function('.counter++.');/ if /{[^}]*\$/" -i.bak
    

    Using GNU sed let you do the job very quickly

    sed -e "/{[^}]*\$/{s/{/{function('.counter++.');/}" -i.bak *
    

    Edit For doing modification only if previous line don’t contain word typedef:

    perl -pe "BEGIN { my \$td=1; };s/{/{function('.counter++.');/ if /{[^}]*\$/ && \$td==1 ; \$td=do{/typedef/?0:1};"  -i.bak *
    

    could be written;

    perl -pe "
    BEGIN { my \$td=0; };
    s/{/{function('.counter++.');/ if /{[^}]*\$/ && \$td==0 ;
    \$td=do{/typedef/?1:0};"  -i.bak *
    

    or more readable as

    perl -pe '
        BEGIN { my $td=0; };
        s/{/{function(\047.counter++.\047);/ if /{[^}]*$/ && $td==0;
        $td=do{/typedef/?1:0};
      ' -i.bak *
    

    Or as a perl script file: cat >addFunction.pl

    #!/usr/bin/perl -pi.bak
    BEGIN { my $td = 0; }
    s/{/{function(\047.counter++.\047);/ if /{[^}]*$/ && $td == 0;
    $td = do { /typedef/ ? 1 : 0 };
    

    Explained:

    • BEGIN{...} command block to do at begin of program.
    • s/// if // && to replacement if current match match and $td=0
    • $td=do{ aaa ? bbb : ccc } assing to td: if aaa then bbb else ccc.

    As perl run sequetialy, $td keep his value until next assignement. So if test for replacement is doing before $td assignement, the check will use previous value.

    And finaly, same using sed:

    sed -e '/{[^}]*$/{x;/./{x;s/{/{function(\o047.counter++.\o047);/;x;};x;};h;s/^.*typedef.*$//;x;' -i.bak *
    

    or more readable:

    sed -e '
        /{[^}]*$/{
            x;
            /./{
                x;
                s/{/{function(\o047.counter++.\o047);/;
                x;
            };
            x;
        };
        h;
        s/^/./;
        s/^.*typedef.*$//;
        x;
    ' -i.bak *
    

    Some sed tricks:

    • h store (backup) current line to the hold space
    • x exchange current working line with the hold space
    • s/// well known replacement string command
    • \o047 octal tick: '
    • /{[^}]*$/{ ... } Command block to do only on lines maching { and no }.
    • /./{ ... } Command block to do only on lines containing at least 1 character
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to implement a history/recent-files functionality for my Perl/ Tk program. Here is
I've got a small Perl program that I want to run on the command
my @matches = ($result =~ m/INFO\n(.*?)\n/); So in Perl I want to store all
I have a Perl program and a C program. I want to run the
I have a Perl program that stores regular expressions in configuration files. They are
I want to capture output of a Perl program and display output data (string
I'm new to Perl and I'm writing a program where I want to force
I need to modify an existing Perl program. I want to pipe a string
Hey all, I have a question about perl objects and threading. My program is
I want to write a program which would download all post offices given a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.