Change all font-size and respect the power of Perl

Boris Kotov
2 min readApr 6, 2019

--

Most Web-Developers are aware of the language called Perl, but they don’t know it, so they aren’t aware of its capabilities.

Some weeks ago, I had to refactor some rem values within my styles. For those who don’t know what these (r)em’s are, here is an example:

<div style=”font-size: 10px” id="base-10">
<div style=”font-size:0.75em”>February 20</div>
<div style=”font-size: 2em”>Hello</div>
</div>

In the example above the base font-size for the #base-10 s 10px, so the Title “Hello” with 2em will be 20px height and the subtitle (Date) will be 7,5px height. So “rem” as root-em refers to the font-size of the html element.

Now, as our knowledge improved lets consider the following situation:

You have to change the base font-size from 10px to 16px but you want that all of your styles are still the same. For example a label with 1.2rem on 10px base, must be converted to 0.75rem for the 16px base.

How would you do it in a code base with 100's of scss/css files and over 1000 occurrences of rem usages?

(Problem: most RegEx implementations do not allow code execution during

You can write a script in any language you want, just try it.. Parse all files perform some regex, get the values out of it, the cast the value to a number, calculate the right output replace the previous value with the new one and save the file.

However, I tried it, and gave up after 3 minutes and 3 lines of code, because I thought, there must be something simpler, and there is: Perl

I knew that Perl is a great language for text manipulation, but I never had to use it actually, because the syntax is somewhat cryptic and I even did’t considered to learn it properly.

But I love the CLI and perl also loves it, so to change all occurrences of rem within my code base from `(X)rem` to `(X/*1.6)rem` all I had to do, is to run this command line expression:

$ perl -pi -e 's/(((\d+)?\.)?\d+)rem/@{[$1 \/ 1.6]}rem/g' `find webapp/src/ -name "*.scss"`

Look at this beauty, I think it’s pretty obvious what it does, and I just wanted to mention, that this is how it should be, and I am glad that perl exists. I respect Perl.

Thanks for reading

PS: In case you have some px values in your code base, which you want to convert to rem.

$ perl -pi -e 's/(((\d+)?\.)?\d+)px/@{[$1 \/ 16]}rem/g' `find webapp/src/ -name "*.scss"`

--

--