File handling doubt

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lilly07
    New Member
    • Jul 2008
    • 89

    File handling doubt

    I have a file with 100 lines. They are all alphabets of 40 in length in each line. How to grab the first character of every line. I can't use the splait function as they are no delimiters. Do i have add every line into an array and get the 0th element? Any other nicer way to do?
    Thanks.
  • nithinpes
    Recognized Expert Contributor
    • Dec 2007
    • 410

    #2
    You can make use of split function without any delimiter, so that split occurs after each character.
    Code:
    while(<FILE>) {
    my @chars = split // ;
    print $chars[0];
    }
    Better approach would be to use a regular expression as below:
    Code:
    while(<FILE>) {
    print $1 if(/^(.)/);     # take out the first character
    }

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      unpack() would be the best function for this purpose:

      Code:
      $foo = "test";
      $first = unpack('A1',$foo);
      print $first;
      much faster than any regexp or substr() which would have been the second best option.

      Comment

      Working...