Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

truncate fields

Status
Not open for further replies.

loryluv

Technical User
May 4, 2005
7
0
0
CA
Hi all,

I have a csv file and I am using the Text::CSV_XS module to parse it. This works fine.
However, for a particular column (the 8th one), I need to truncate the field to only having 50 characters. For example, if the field has 90 characters in total, I need to delete everything from the 51st character and onwards. If the field contains only 30 characters, then do nothing. I'm not sure how I can do this in Perl. Is there a function that counts the number of characters in the field?

Thanks a lot for the help!
-Lory
 
If you pass the field into a variable then you can use only 50 characters of this variable by using substr.
And you can check the number of characters using length or a regex.

Something like this
Code:
if (length $field > 50){
    $field = substr ($field, 0, 50);
}

or

if ($field !~ /^\w{,50}$/){
    $field = substr ($field, 0, 50);
}

Now if $filed has more than 50 char you will use only 50 of them. Starting from position 0, and ending to position 50.
If it has less it will do nothing.


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Thanks Perluserpengo! It works great :)
Thanks a lot!
 
According to the docs, you should be able to simplify that to:
Code:
$field = substr ($field, 0, 50);
substr EXPR,OFFSET,LENGTH
...
If OFFSET and LENGTH specify a substring that is partly outside
the string, only the part within the string is returned.
In other words, you don't have to check the length of the string because substr does the right thing.

 
That is true philote well done.



``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top