1

Say I have a file called hello.txt which contains "Hello World!". If I wanted to make a script which opened the file and read the contents (I know how to do that) and added stuff to the string, how would I go about doing this?

For example: Hello World would have '..' inserted at the start of the string/content, and then every 2 characters later, except at the end. Also consider the contents will not always be "Hello World".

1 Answer 1

2

Since you already know how to read from a file, I take it your only real question is how to add .. after every 2 characters of any given string:

my $string = "Hello World";
$string =~ s/^|(..)(?!$)/$1../g;
print "$string\n";

Output:

..He..ll..o ..Wo..rl..d

Though I can't imagine how that would ever be useful.

The regex looks for the start of string or two characters not followed by the end of the string, using negative look-ahead, and replaces all matches with any captured characters followed by two periods.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you a lot. One more question, say HelloWorld is all attached, this will output .. at the very end. Is there a way to prevent this?
@DavidG: I missed that part before I wrote my original answer. It's avoided with the negative look-ahead for the end of string added to my revised answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.