1

** I have a follow-up question that is marked with '**' **

I was asked to write Perl code that replaces every { with {function(<counter>) and in every replacement the counter should get larger by 1. e.g. first replacement of { will be {function(0) , second replacement of { will be {function(1) etc. It suppose to do the replacement in every *.c and *.h file in a folder including subfolders.

I wrote this code :

#!/usr/bin/perl
use Tie::File;
use File::Find;
$counter = 0;
$flag = 1;

@directories_to_search = 'd:\testing perl';
@newString = '{ function('.$counter.')';
$refChar = "{";
finddepth(\&fileMode, @directories_to_search);


sub fileMode 
{
 my @files = <*[ch]>;   # get all files ending in .c or .h
 foreach $file (@files) # go through all the .c and .h flies in the directory  
{
    if (-f $file)  # check if it is a file or dir
    {
    my @lines;
# copy each line from the text file to the string @lines and add a function call after every     '{' '
    tie @lines, 'Tie::File', $file or die "Can't read file: $!\n";
    foreach ( @lines )
    {
        if (s/{/@newString/g)
        {
            $counter++;
            @newString = '{function('.$counter.')';
        }
        untie @lines; # free @lines
    }
    }
}   
}

The code searches the directory d:\testing Perl and does the replacement but instead of getting {function(<number>) I get {function(number1) function(number3) function(number5) function(number7) for instance for the first replacement I get {function(0) function(2) function(4) function(6) and I wanted to get {function(0)

I really don't know what is wrong with my code.

An awk solution or any other Perl solution will also be great!


* I have a follow-up question. now I want my perl program to do the same substitution in all the files except the lines when there is a '{'
and a '}' in the same line. so i modified the code this way.

#!/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
#foreach $filename (@ARGV) 
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";
    #$_='{function(' . $counter++ . ')';

    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();'

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 would really appreciate some help.

Thank You!!

2
  • 1
    Why do you use both File::Find and a glob to find files? That is doing the same job twice, you know.
    – TLP
    Jan 9, 2013 at 12:47
  • I do not see you add the string "number" to anything in your code. Are you sure that you mean that you see "number1", "number3" etc in your output?
    – TLP
    Jan 9, 2013 at 12:51

4 Answers 4

3

This is a simple matter of combining a finding method with an in-place edit. You could use Tie::File, but it is really the same end result. Also, needless to say, you should keep backups of your original files, always, when doing edits like these because changes are irreversible.

So, if you do not need recursion, your task is dead simple in Unix/Linux style:

perl -pi -we 's/{/"{ function(" . $i++ . ")"/ge' *.h *.c

Of course, since you seem to be using Windows, the cmd shell won't glob our arguments, so we need to do that manually. And we need to change the quotes around. And also, we need to supply a backup argument for the -i (in-place edit) switch.

perl -pi.bak -we "BEGIN { @ARGV = map glob, @ARGV }; s/{/'{ function(' . $i++ . ')'/ge" *.h *.c

This is almost getting long enough to make a script of.

If you do need recursion, you would use File::Find. Note that this code is pretty much identical in functionality as the one above.

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

my $dir = "d:/testing perl";   # 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;
    print;
}

Don't be lulled into a false sense of security by the backup option: If you run this script twice in a row, those backups will be overwritten, so keep that in mind.

4
  • Doesn't the curly need to be preserved?
    – Zaid
    Jan 9, 2013 at 13:17
  • Right, didn't notice that.
    – TLP
    Jan 9, 2013 at 13:20
  • what does it mean preserved?
    – MiSo
    Jan 9, 2013 at 14:02
  • @MichaelSogolovsky Preserve means "keep", and it is fixed now. Most perl answers here use the same basic regex, so your biggest problem is file finding and editing, I would say.
    – TLP
    Jan 9, 2013 at 14:04
2
$ perl -pi -e 's| (?<={) | q#function(# . ($i++) . q#)# |gex' *.c *.h
0
1

It can be done in a single line as below:

perl -pi -e 's/({)/"{function(".++$a.")"/ge;' your_file

I have just taken an example input file and tested too.

> cat temp
line-1 {    {    {   {
line-2 {    {   {
line-3 {    {
line-4 {

Now the execution:

> perl -pi -e 's/({)/"{function(".++$a.")"/ge;' temp
> cat temp
line-1 {function(1)    {function(2)    {function(3)   {function(4)
line-2 {function(5)    {function(6)   {function(7)
line-3 {function(8)    {function(9)
line-4 {function(10)
2
  • Except you don't need to initialize $a when using ++, and the OP is using windows, so argument handling and in-place edit (which you don't use) won't work.
    – TLP
    Jan 9, 2013 at 13:25
  • Updated my answer removing the BEGIN block and adding an inplace replacement.
    – Vijay
    Jan 9, 2013 at 13:37
1

Using awk '/{/{gsub(/{/,"{function("i++")");print;next}{print}' and your code as input:

$ awk '/{/{gsub(/{/,"{function("i++")");print;next}{print}' file
sub fileMode 
{function(0)
 my @files = <*[ch]>;   # get all files ending in .c or .h
 foreach $file (@files) # go through all the .c and .h flies in the directory  
{function(1)
    if (-f $file)  # check if it is a file or dir
    {function(2)
    my @lines;
# copy each line from the text file to the string @lines and add a function call after every     '{function(3)' '
    tie @lines, 'Tie::File', $file or die "Can't read file: $!\n";
    foreach ( @lines )
    {function(4)
        if (s/{function(5)/@newString/g)
        {function(6)
            $counter++;
            @newString = '{function(7)function('.$counter.')';
        }
        untie @lines; # free @lines
    }
    }
}   
}

Note: The function number won't be incremented for inline nested {.

$ echo -e '{ { \n{\n-\n{' | awk '/{/{gsub(/{/,"{function("i++")");print;next}1'
{function(0) {function(0) 
{function(1)
-
{function(2)

Explanation:

/{/                               # For any lines that contain {
gsub( /{/ , "{function("i++")" )  # replace { with function(i++)
print;next # print the line where the replacement happened and skip to the next
print                             # print all the lines 
4
  • thank you for your quick response. could you please explain to me how it works. by using awk I ment system call.
    – MiSo
    Jan 9, 2013 at 13:19
  • @MichaelSogolovsky I have added an explanation. Jan 9, 2013 at 13:25
  • thank you for your quick response. could you please explain to me how it works? This line is replacing '{' in one file? instead of 'file' i need to indicate the file's name? or path? And again Thank you!
    – MiSo
    Jan 9, 2013 at 13:25
  • Yes just pass your actual file. Jan 9, 2013 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.